April 21, 2012

How a simple rule can make your code bulletproof

No matter what programming language you use, if it has objects, you likely make the same mistake as I used to do. And is not even your fault because that was the way you learned to code, because the teachers, books or tutorials don't like to talk about murdane things even if they are vital.

Null pointers

What am I talking about? I'm talking about the number one cause of bugs : null pointers. Suppose we have a function that draws a circle. The function needs a Circle object parameter to know how to draw the circle.
public drawCircle(Circle circle){
 int radius=circle.getRadius();
   
 //draw circle here 
}
Sooner rather then later, somebody will call the function with null:
drawCircle(null);
Since circle is null, the circle.getRadius() call will throw null pointer exception. That will stop the execution thread, no code after that line will be executed. A simple mistake like this in only one method in only one source file can crash an app with thousand of methods and source files. One mistake is enough.

A simple rule

There is a simple and effective way for the above problem, ALWAYS check any object you get from outside for null:
public drawCircle(Circle circle){
 int radius= null!=circle ? circle.getRadius() : 0;
   
 //draw circle here 
}
I wish some day teachers, books and tutorials will talk about simple things like this over and over again. I wish they will teach code that doesn't crash.

No comments:

Post a Comment