Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Preventing Nested Code Blocks

1.00/5 (1 vote)
12 Mar 2010CPOL 1  
How to prevent nested code blocks
In this tip, you will find two basic rules to prevent nested code blocks.

Introduction

The easiest readable and maintainable code, is code that contains no nested blocks.

Although sometimes unavoidable, preventing nested code blocks should be part of any coding guideline.
Two basic rules are listed below:

  1. Exit First Rule
  2. Delegate

Rule 1 simply means that first any condition must be checked that may lead to an early exit of the method, e.g., consider (pseudo code):

C++
void MyMethod(...)
{
   if (x > 0)
   {
      // do your stuff here
   }
}

This can be refactored to:

C++
void MyMethod(...)
{
   if (x <= 0)
       return; // exit early, or throw exception

   // do your stuff here

}

Rule 2 Delegate means that any loop that contains another loop should be delegated to and executed by another method.

Example: Consider (pseudo code):

C++
// method will calculate the faculty of x (non-recursive)
int MyMethod(int x)
{
    if (x < 1) return 0;  // exit first rule
    if (x == 1) return 1;  // exit first rule

    int result = 0;
    while (x < max)
    {
        for (int i = 0; i < x; i++)
        {
           //do stuff here;
        }
        x++;
    }
}

The inner loop should be put in a separate method. This will not only increase readability but also increase code reuse, maintainability, and reduce code complexity, like so:

C#
// method will calculate the faculty of x (non-recursive)
int MyMethod(int x)
{
    if (x < 1) return 0;   // exit first rule
    if (x == 1) return 1;  // exit first rule

    int result = 0;
    while (x < max)
        result += MySubCalculation(x);

    x++;
}
C#
int MySubCalculation(int x)
{
   // put any exit firsts here

  for (int i = 0; i < x; i++) 
  {
      //do stuff here;
  }
}

History

  • 12th March, 2010: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)