How do I avoid returning NULL to a function (JAVA)?

Suppose I have List<SomeObject>

and have a function that returns a reference to this object, if available.

SomeObject GetSomeObject(List<SomeObject>, int x){
    /* Search for object in list that has a properties
        with value x */

    if (found)
        return /* The object found */
    else
        return NULL;
}

void DoSomething(SomeObject S){
    if(S!=NULL){
        /* Do action 1 */
    }
    else{
        /* Do action 2 */
    }
}

      

I read somewhere that returning is NULL

not part of clean code. So I was wondering what the equivalent code is for this case.

UPDATE: I have read this question and I think my case is different. In this case, if it NULL

returns, do nothing, but I need to do something if it NULL

returns

+3


source to share


4 answers


If you're using Java 8, consider the Optional class , but note that it doesn't apply everywhere.

Many people think (myself included) that it Optional

should only be used for return values, not for parameters, and especially for object attributes. However, as always, there is no hard and fast rule, just be careful not to replace the non-null call with Optional

blindly, not knowing if you are getting any benefit from it.



The sample code, for example, Optional

will not do you any good. Since you are performing some action regardless of zero or not, you just change if(s == null)

to if(s.isPresent())

. However, if the logic did something only if s is not null, without else

you can use Optional.ifPresent()

it to make things cleaner. Of course, Optional

there are other useful methods that will give you cleaner code, for example orElse()

, that you can effectively use to use the default values.

+6


source


It sounds like you mean a special case pattern (implementation specific - Option or Null Object ).

There are Java implementations like Option named Optional

, in Java 8 and in Guava .

In your case, you will use Optional<SomeObject>

and have this implementation (I am using Guava implementation):



Optional<SomeObject> getSomeObject(List<SomeObject>, int x) {
    /* Search for object in list that has a properties
        with value x */
    if (found) {
        return Optional.of(objectFound);
    } else {
        return Optional.absent(); // or Optional.empty(); in Java 8
    }
    // if objectFound variable is null when not found, you can simply use
    // return Optional.fromNullable(objectFound);
    // or return Optional.ofNullable(objectFound); in Java 8
}

      

So the code is self-explanatory about returning an optional object. Then you will have:

void doSomething(Optional<SomeObject> o) {
    if (o.isPresent()) {
        SomeObject someObject = o.get();
        /* Do action 1 */
    } else {
        /* Do action 2 */
    }
    // or opt.map(/* action 1 */).orElse(/* action 2 */); in Java 8
}

      

+4


source


You can throw a NoSuchElementException , this goes well with the "fail fast" metadology .

However , if your code starts to use the exception mechanism for flow control - this is a very big no-no, and you should avoid it. A good rule of thumb is to throw an exception if the element does not exist, only if your API also supports method contains()

(s HasSomeObject(obj)

).


Disclaimer: This answer is suitable for java-8 code, for java8, better practice would probably be optional as suggested by @Kayman

0


source


One general approach that you might consider is the Null Object Pattern .

Instead of returning NULL, you are returning an instance of the correct type of object, which simply does nothing when you call its methods. It doesn't work in all cases, but it's worth considering.

0


source







All Articles