Search code examples
javadesign-patternsrefactoringnullnull-object-pattern

Interesting thought problem on refactoring code that returns a null


I am interested in hearing your feedback. I've recently seen some Java code that is implemented in the following way:

Object1 SomeMethod(String key) {
    Object1 object1 = null;
    List<Object1> objectList = getAllRecordsWithKeyFromDatabase(key);
    if (!objectList.isEmpty()) {
        object1 = objectList.get(0);
    }
    return object1;
}

void AnotherMethod() {
    ...
    Object1 object1 = SomeMethod(key);
    if (object1 == null) {
        // throw exception
    }
    // continue working
}

I am always concerned whenever a null is returned without context. I would rather the response from SomeMethod be more explicit and was considering refactoring it. Throwing an exception from SomeMethod could offer a way to do this. It would be in context and occur at the point of failure.

I am wondering if there is another way where SomeMethod could inform AnotherMethod that 'nothing was found in the database' instead of assuming that null always equaled 'not found'. I thought that a NullObject could be used, but it is unclear to me how AnotherMethod should avoid 'continue working' if the data was not found.

How would you refactor the code?


Solution

  • I don't see a problem with it as it, except that I would clearly document that SomeMethod can return null in some cases.

    However, if finding null is clearly an exceptional case, then throwing an exception is the right approach. If you change AnotherMethod so that it declares a checked exception, then your intent would be much clearer to users of that method. Something like this:

    void AnotherMethod() throws SomethingBadHappenedException {
      //snip
    }