-
February 28th, 2011, 10:50 PM
#1
Nested If Statements
Hello, I wanted to get your opinion on the use of nested ifs. What depth is considered absolutely unacceptable? Basically I have a construct like this (can't post the actual code):
Code:
void test()
{
if(...)
{
if(...)
{
if(...)
{
//code
}
else
{
//code
}
}
else
{
//code
}
}
else
{
//Code
}
}
I believe I have a legitimate reason for nesting this deeply. In addition, with the actual code, I believe it makes sense to do so. So, would this be acceptable or would try to find another way? Even if it meant rewriting code in various files? Thanks for any input.
-
March 1st, 2011, 01:34 AM
#2
Re: Nested If Statements
This is individual preference. Of course, too deep nesting makes a program unreadable. If you feel that this code is unreadable, you can change it by this way:
Code:
void test()
{
if( ! ... )
{
// code
return;
}
if( ! ... )
{
// code
return;
}
if( ... )
{
//code
}
else
{
//code
}
}
-
March 1st, 2011, 02:18 AM
#3
Re: Nested If Statements
I would prefer to move the inner if/else part to a separate method. It makes things more readable, IMHO.
-
March 1st, 2011, 02:21 AM
#4
Re: Nested If Statements
There is no definite answer, but whenever a function becomes too long/deep, you may want to consider splitting it into (sub)functions.
Also, see if you can't rework the logic, and not fall in the dreaded if(valid) if(valid) if(valid).
It mainly depends on the content of those ifs you got there. It also helps when all your objects are RAII, as you can just bail out any time.
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
-
March 2nd, 2011, 11:36 AM
#5
Re: Nested If Statements
I figured it would depend on the situation. I realize that ultimately if the nests become 4th or 5th level nests, then there is definitely a problem. Luckily the logic had to change anyway and that got rid of the innermost if else block in the example above, so I think this is certainly acceptable. Thanks for the input.
-
March 2nd, 2011, 02:07 PM
#6
Re: Nested If Statements
I'll usually go three to five levels deep (but 5 have to be only a line or two) before pulling it out into it's own method.
There are other ways to deal with that though, like Alex F noted. If I get things that nest too deeply, I tend to actually simply rearrange it as oppose to creating methods.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|