Do not return null

Filed under: Tools, — Tags: IntelliJ IDEA, never return null, null, return null — Thomas Sundberg — 2011-07-28

Using your IDE to automatically create methods for you maybe a disaster waiting to happen.

When test driving your code, you always start with a test. The test will then demand that some functionality is implemented. Modern IDEs are a great support in this. All you have to do is to mark the class or method in your test that isn't implemented and have your IDE implement it for you. An IDE cannot know what you should implement and will therefore create a rude, but compiling suggestion. This often means an implementation like this:

public Car create(Car car) {
    return null;
}

This is fine if you execute this code the first thing you do. You will then implement it properly and make sure that the test passes. But what happens if you mock the behaviour and make sure that the interactions works? Then chances are that you forget about the return null above. A NullPointerException is waiting to be thrown.

I have started to use another approach, throw a sun.reflect.generics.reflectiveObjects.NotImplementedException instead. It is harmless and you cannot get past it when executing your code. It signals that this is an area where the developer were planning to return and fix, but forgot.

An example could be:

public Car find(String registrationNumber) {
    throw new NotImplementedException();
}

Is it better to throw an exception instead of returning null? I think so, null is sneakier and has a better chance to slip away than an exception. If the exception never is thrown, it is just an indication that this particular code never is executed and could be removed.

Change the default IDE behaviour

I use IntelliJ IDEA and changing the default behaviour is done in

Preferences | File Templates | Code | Implemented Method Body and New Method Body

My new settings are

#if ( $RETURN_TYPE != "void" ) throw new NotImplementedException();#end

Resources



(less...)

Pages

About
Events
Why

Categories

Agile
Automation
BDD
Clean code
Continuous delivery
Continuous deployment
Continuous integration
Cucumber
Culture
Design
DevOps
Executable specification
Git
Gradle
Guice
J2EE
JUnit
Java
Javascript
Kubernetes
Linux
Load testing
Maven
Mockito
New developers
Pair programming
PicoContainer
Presentation
Programming
Public speaking
Quality
React
Recruiting
Requirements
Scala
Selenium
Software craftsmanship
Software development
Spring
TDD
Teaching
Technical debt
Test automation
Tools
Web
Windows
eXtreme Programming

Authors

Thomas Sundberg
Adrian Bolboaca

Archives

Meta

rss RSS