Handmade Hero » Forums » Code » Avoiding too much nesting.
jpmontielr
Juan Pablo Montiel
5 posts
#12077 Avoiding too much nesting.
6 months, 2 weeks ago

Hi There! Regarding nesting, I know Casey has said it is not an issue for the most part, but I was wondering if there is a way to avoid too much nesting? I understand it is not an issue performance-wise, but being 5 or 6 levels in nesting really does hurt my understanding of the code, maybe this is an issue only for me, but are there any other options besides deep nesting?
mmozeiko
Mārtiņš Možeiko
1518 posts
1 project
#12078 Avoiding too much nesting.
6 months, 2 weeks ago Edited by Mārtiņš Možeiko on June 1, 2017, 7:55 p.m.

Yeah, I also don't like his style. I usually try to write code to have as little as possible nesting.

So instead of:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void f()
{
  if (a)
  {
    if (b)
    {
      while (c)
      {
        if (d)
        {
          ...
        }
        else
        {
          ... 
        }
      }
    }
  }
  else
  {
    foo();
  }
}

I write:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void f()
{
  if (!a)
  {
    foo();
    return;
  }

  if (!b)
  {
    return;
  }

  while (c)
  {
    if (d)
    {
      ...
      continue;
    }
    ... 
  }
}


Or I split function in smaller parts - most inner nestings go into separate functions that I call.
jpmontielr
Juan Pablo Montiel
5 posts
#12081 Avoiding too much nesting.
6 months, 2 weeks ago

Ohh, that's exactly the kind of example I was looking for, thank you Martins! I will experiment with that, I like what you did there quite a lot. Usually as soon as I hit 3 nesting levels I start to get anxious.