Search code examples
javanullpointerexceptionnulldaonull-object-pattern

DAO with Null Object Pattern


After Reading:
Effective Java (See Item 43) - Joshua Bloch
Clean Code (Don't Return Null) - Uncle Bob
Avoiding != null statements
Null Object pattern

I was looking for an answer to the question of what a DAO should return when a search ends up to be for an entity that does not exist for non-collection objects. Collection object is really ok by using empty array or emptyList methods. But with non-collections it might be harder. An alternative solution is to never return null and instead use the Null Object pattern. But I have no idea to integrate with Null Object pattern with DAO and I really excited to see great integration with Null Object pattern and DAO pattern especially for model(dto) object return case.

I would appreciate and welcome any best design pattern, scenario and suggestion.


Solution

  • Indeed introducing null reference is probably one of the worse mistake in the programming languages' history even its creator Tony Hoare calls it his billion-dollar mistake.

    Here are the best alternatives to null according to your Java version:

    1. Java 8 and above

    Starting from Java 8 you can use java.util.Optional.

    Here is an example of how you could use it in your case:

    public Optional<MyEntity> findMyEntity() {
        MyEntity entity = // some query here
        return Optional.ofNullable(entity);
    }
    

    2. Prior to Java 8

    Before Java 8 you can use com.google.common.base.Optional from Google Guava.

    Here is an example of how you could use it in your case:

    public Optional<MyEntity> findMyEntity() {
        MyEntity entity = // some query here
        return Optional.fromNullable(entity);
    }