tags:

views:

166

answers:

4

Ok - I have someone I work with who has written somthing like this

if()
   if()
      if()
         if()
         if()

I dont like this!!

If there are ten different boolean flags how many combinations are there?

10 factorial?

I am trying to explain why this is bad

+3  A: 

2 in 10th degree = 1024

I am trying to explain why this is bad

This may not necessarily be bad. Each condition cuts off a half of the cases. If you know you only need to do something when the first condition is true, you drop 512 cases already. That's the point of those checks.

You can however rewrite it to be better looking and more readable:

if(c1 && c2 && c3 && c4 && c5)
Developer Art
That is to say, 2**10, or 1024.
Ignacio Vazquez-Abrams
@Ignacio: You mean 2^10 . ;)
Bobby
@Bobby: Smart programmers know that 2^10 equals 8 ;P
Ignacio Vazquez-Abrams
try `2<sup>10</sup>`.
Kobi
+2  A: 

Two states per flag and 10 flags means 2^10 = 1024

David Kanarek
+1  A: 

Most good static code analysers have a maximum level of indentation for this exact reason. It becomes very difficult to handle all logical cases with such high levels of nesting.

Is this the typical newbie error of checking all error conditions in one big lump at the top of a function?

If so, you might like to get the author of the code to change it to a sequence of if statements rather than this heavily nested construct.

if(error1) {
    /* report error 1 and exit */
}

if(error2) {
    /* report error 2 and exit */
}

if(error3) {
    /* report error 3 and exit */
}

...

Makes it much easier to test the code and also to provide tailored information about a specific error rather than one generic "something's bad" statement.

Rob Wells
Makes it harder to refactor if there are multiple return statements...
ck
@ck, Not at all if the intent of the return statements is clear, as in six return statements in a function. Five at the top for individual error cases and one at the bottom for a good result.However, having return statements dribbled all around a function returning different things *is* definitely a pain to refactor!
Rob Wells
A: 

At most 2^10 = 1024 paths (the maximum is reached if the conditions are fully independent)

Having many paths in one method is called having a high complexity. This high complexity impacts on maintainibility and on the testability. Obviously complex methods are more error prone and more difficult to test and maintanin.

Complexity is not necessarily a problem: some solutions to problems have an inherent complexity that cannot be removed. In other words some problems have definitively difficult to find solutions. In these cases you can reduce the local complexity by splitting the complex methods in smaller ones (this does not reduce the global complexity obviously).

In the other cases remove the additional complexity: find a simpler solution (easy to say, I know) ;-)

jdehaan