Clean code

Writing cleaner conditional statements

Just a thought on using cleaner code while using a lot of nested if statements.

Clean code

Clean code

Ugly code

if(process_x()) {
    /* do a lot of other things */
    if(process_y()) {

         /* do a lot of other things */
         if(process_z()) {
              /* do a lot of other things */
              /* SUCCESS */
         }
         else {
              clean_all_processes();
         }
    }
    else {
         clean_all_processes();
    }
}
else {
    clean_all_processes();
}

Good looking code

do {

  if( !process_x() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_y() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_z() )
    { clean_all_processes();  break; }

  /* do a lot of other things */
  /* SUCCESS */

} while (0);

The use of goto is an alternative, the bad thing about this is you always need to define the label.

Advertisements