1

The code runs like this, as the code increases it becomes unreadable

if(!cond1){
    //print error
}else{
        if(!cond2){
          // print error
        }else{
               //code goes on.....
             }
     }

Alternative way of writing the above code will be very helpful

FirmView
  • 3,130
  • 8
  • 34
  • 50
  • It depends on language and larger context. "Not Constructive". (I prefer to avoid needless nested `if` statements, though .. C-style languages have the hanging `else if` construct.) –  Jul 23 '12 at 20:10
  • Possibly look at using a switch case if appropriate: http://stackoverflow.com/q/395618/609908 and http://stackoverflow.com/q/335971/609908 – Amalea Jul 23 '12 at 20:12

3 Answers3

0

It is easier to understand/debug if you use the blocks to execute the true conditions. It is because when something is true is a narrower condition than when something is not true.

if (cond1){

}else if (cond2){

}else{

}
srini.venigalla
  • 5,137
  • 1
  • 18
  • 29
0

This is usually handled with guard clauses instead of nested or chained ifs:

if (! cond1)
    throw error 1;
if (! cond2)
    throw error 2;

perform action;

Note that this assumes that the function actually returns upon error, otherwise this will lead to faulty behaviour. However, this is recommended. In general, don’t try to resume an action in the face of errors, yield control to a higher level in your application’s logic as soon as possible.

In particular, the “print error” aspect should almost (?) always be disconnected from the actual logic – otherwise you are violating the single responsibility principle.

As a consequence, let your logic-performing function exit early when an error condition is detected, and let other functions take care of printing those errors.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

Depending upon the complexity, you might consider breaking conditions up into their own functions, and restructuring into something like:

if (!f1() && !f2() ... ){
    ...
}

Then let each individual condition's function handle that particular error instead of cluttering up the top-level function.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284