Early abort idiom

Take a look at those Java code snippets:

public void insert(Order order)
   if(order != null) {
      // insert code here
   }
}

public void insert(Order order)
   if(order == null) {
      return;
   }
   // insert code here
}

The second code scratch is said to increase the Thomas McCabe’s cyclomatic complexity. The cyclomatic complexity is a model metric instead of implementation metric, as you may think. An example about implementation metric is LOC (Lines of Code). When I was in college, I learned the McCabe’s metric measures the number of control flow statements and return statements of your code, but it doesn’nt count the normal return statement of your methods. So, the McCabe metric is two for the first code and two for the second. McCabe says that the computation complexity rises with the increase of the execution routes. Cedric has an interesting opinion about this subject. Particularly, I think when you try to use the first insert(Order order), you end up having some nested if’s, your code tends to be a little messy. The second one focus on the basic flow of your method, that is, the normal bahavior its expected to have. In my daily basis, sometimes I apply the first one, sometimes the second one. And you? Do you think in cyclomatic complexity when you are coding?

One Reply to “Early abort idiom”

  1. I’m much more found of the ‘fail fast’ style, keeping local artificial control variables just to increase the number of if-else’s of your code is just not pratical nor it helps your code to be clearer. By the way, Eclipse can highligh all exit points of your method if you only position the cursor at the type of the return value and press Alt+Shift+O or use the menu option ‘Mark Occurrences’. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *