0

Issue

Attempting to identify which is the best practice for executing sequential methods. Either, nesting conditionals one after another, or nesting conditionals one inside another, within a main function. In addition, if you could supply "why" one method would be better than the other besides what's most acceptable, I'd sincerely appreciate it. Here are my examples:

Nesting one after another

int main()
{
    // conditional 1
    if (!method_one())
    {
       ... do something
    } 
    else 
    {
       ... prompt error for method 1!
    }

    // conditional 2
    if (!method_two())
    {
       ... do something
    } 
    else 
    {
       ... prompt error for method 2!
    }

    // conditional 3
    if (!method_three())
    {
       ... do something
    } 
    else 
    {
       ... prompt error for method 3!
    }

    return 0;
}

Nesting one inside another

int main()
{
    // conditional 1
    if (!method_one())
    {
       if (!method_two())
       {
          if (!method_three())
          {
              ... next steps in sequence
          } 
          else 
          {
             ... prompt error for method 3!
          }
          ... prompt error for method 2!
       }
       ... prompt error for method 1!
    }

    return 0;
}

Observations

I've seen both used, however, not sure which is better practice and/or more commonly acceptable.

Justin Byrne
  • 179
  • 1
  • 2
  • 12

1 Answers1

0

The two options aren't actually entirely logically identical - in the "Nesting one after another", for example, method_two() will run even if method_one() fails; if method_two() has any side effects this may be undesirable. Furthermore, if both method_one() and method_two() are destined to fail, "Nesting one after another" will print two error prompts, whereas 'Nesting one inside another" will only error prompt on method_one().

You could close the difference by appending a goto End at the end of each else in "Nesting one after another", so it skips over the remaining checks, but the use of goto would probably get you slapped. Alternatively, you could return at the end of each else, perhaps with an error code, and let whoever is calling your main function deal with understanding what went wrong.

With that in mind, "Nesting one after another" is probably easier to read and understand, since there's less indentation/the code is kept flat, and what happens on failure is immediately next to the check. (That 2nd point can be addressed by reordering the error prompt for method_one() to before the check for method_two() for "Nesting one inside another")

10762409
  • 523
  • 4
  • 19