Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many nested code blocks do you end up with in practice when coding?

Tags:

coding-style

I just finished writing a function that has ended up with nested code blocks something like the following:

class ... {
  void Method() {
    while (...) {
      ...
      switch (...) {
        while (...) {
          switch (...) {
            if (...) {
            }
          }
        }
      }
    }
  }
}

Do you find this is standard in your day-to-day coding work, or do you quickly set about trying to redesign and break up the code when you see something like this?

like image 818
Yawar Avatar asked Nov 28 '22 15:11

Yawar


2 Answers

never more than three. as my personal philosophy. However, there are cases where you cannot do better. A typical case is: suppose you have to iterate on all the elements of a 6-indexes matrix. Not your typical case, but sometimes it happens.

So, you could refactor out, say, the innermost three loops. Good... How do you call the routine you refactor ?

In the end, you realize that the highly nested loop is the best for future understanding. Of course this is a special case. If you do have highly nested loops and switches like the one you paste, then you do have a problem, and you should consider giving meaningful names to the various parts, isolate them, tackle the switch with object-orientation, etc..

like image 177
Stefano Borini Avatar answered Feb 08 '23 23:02

Stefano Borini


I would be very worried about the switch-within-switch construct. That should "never" happen. Especially under the light of questions like this ("using switch is bad OOP style?").

like image 24
David Schmitt Avatar answered Feb 09 '23 01:02

David Schmitt