Null, Validations and Exceptions

Null The billion Dollars Mistake

So if you did not watch, you should watch this video from Tony Hoare. Long Story short, Null is dangerous and often could means 2 things (error or empty value) which is tricky by itself. We should avoid using null, however in most languages, null is part of ecosystem libraries and frameworks. Another issue of Null is that when you company code grows you end up allowing null for backward compatibility(happens a lot). If you are building and designing a shared library either you get it right from the getgo or you might have lots of refactorings to do in order to improve things.

Validations First

I learn to code with the principle of validations first. The first thing you do in any method or function is to validate the parameters. That’s also the OOP Constructor rule. When you apply validations first you can avoid all sorts of errors and makes the usability of a library/service much better. One approach you could do is the Notifications Pattern. Several libraries do validations in a central and generic class. Validations are also often called Pre-Conditions(Look Guava for instance), Assertions, and Checkers. Java also(since java 7) has the Objects(Sample code in Apache Commons) that makes it easier to do validations.

Exceptions Best Practices

Effective Java(3rd edition) is a great book to get more from Java. There is a section just about proper exception which can be summarized as:

  • Public/protected methods use @throws on Javadoc
  • Objects.requireNonNull
  • @Nullable when the parameter can be null
  • Non-public method(private) can check parameters with assertions (assert)
  • Item 69: Use Exception only for exceptional conditions (Dont use for ordinary control flow)
  • Item 72: Favor the use of Standard Exceptions
  • Item 73: Throw Exceptions appropriate to the abstraction (High level would catch lower level)
  • Item 74: Document all exception throw by each method (/** Javadoc @throws */
  • Item 75: Include failure capture information in the detail message
  • Item 76: Strive for failure atomicity (Generally Exception should leave the object how it was before the exception)
  • Item 77: Don’t ignore Exceptions

Functional Programing and Modern Ways to handle errors

For functional programming we have the Monad Maybe also know in java as Optional which IMHO works much better than returning null and much better than returning exceptions. If you look Go language for instance you are forced to deal with errors after each function execution. Which is an interesting and very simple way however it can get a bit tedious?



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store