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:
- Exit First Rule
- 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):
void MyMethod(...)
{
if (x > 0)
{
}
}
This can be refactored to:
void MyMethod(...)
{
if (x <= 0)
return;
}
Rule 2 Delegate means that any loop that contains another loop should be delegated to and executed by another method.
Example: Consider (pseudo code):
int MyMethod(int x)
{
if (x < 1) return 0; if (x == 1) return 1;
int result = 0;
while (x < max)
{
for (int i = 0; i < x; i++)
{
}
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:
int MyMethod(int x)
{
if (x < 1) return 0;
if (x == 1) return 1;
int result = 0;
while (x < max)
result += MySubCalculation(x);
x++;
}
int MySubCalculation(int x)
{
for (int i = 0; i < x; i++)
{
}
}
History
- 12th March, 2010: Initial version
Currently Herre Kuijpers is employed at Rubicon. During his career he developed skills with all kinds of technologies, methodologies and programming languages such as c#, ASP.Net, .Net Core, VC++, Javascript, SQL, Agile, Scrum, DevOps, ALM. Currently he fulfills the role of software architect in various projects.
Herre Kuijpers is a very experienced software architect with deep knowledge of software design and development on the Microsoft .Net platform. He has a broad knowledge of Microsoft products and knows how these, in combination with custom software, can be optimally implemented in the often complex environment of the customer.