Tired of checking for null arguments in the method body

One thing I find annoying at times is adding in null checks in a method body to throw an IllegalArgumentException for method arguments that shouldn't ever be null.

Most of the time as programmers we skip it and rely on the fact that a null pointer will get thrown somewhere further down in the method body. That's not ideal though, especially in a non-transactional system where you can't rollback easily (e.g. writing data to a file or network). I also find myself looking at API's sometimes wondering if a certain field is optional and then going to the javadoc only to find no mention of what happens if I pass in a null for a seemingly optional field.

Ensuring that a method argument is non-null is so cookie cutter that I feel like it should be part of Java. We can declare objects as final so they can only be assigned once, why not be able to declare them as required or notnull so that they can never be assigned null? For example I would like to write a method that looks like this:

public Foo doSomething (final required Bar bar) {
	// Passing in null would throw an IllegalArgumentException
	// or a brand new RequiredArgumentException

rather than what we currently have to do if we want to guarantee that a non-primitive is not null:

public Foo doSomething (final Bar bar) {
	if (bar == null) {
		throw new IllegalArgumentException("bar is required");
	// Now that we've established bar is not null we can start doing
	// non-transactional stuff like writing to a file or network

I also find the former more readable than the latter since even without good javadoc I know it's expecting a non-null value based on the method signature.

This entry was posted in Java. Bookmark the permalink.