In Java, we’re told to check for nulls to avoid unexpected null pointer exceptions. This can be taken too far though. Consider the following code:
StringBuilder builder = new StringBuilder(): if ( builder != null ) { builder.append("data"); }
When did builder have the opportunity to become null? By definition, a constructor creates an object. We just called the constructor. We know builder isn’t null. Having extra code around just invites confusion. It leaves the reader of the code wondering if they are misunderstanding something. Worse , it is a form of dead code. The if statement will never be false so it serves no purpose.
When universities teach programming, they often leave out the parts about how to make code readable and easy to maintain for others. Whether that “other” is yourself in six months or someone else, it is still professional to make the code easy to maintain.
The extra null check certainly isn’t anywhere near the worst example of unmaintainable code I’ve seen. I’ll blog more examples of this in the future.