Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid returning NULL value in a function (JAVA)?

Tags:

java

oop

null

Supposed I have a List<SomeObject> and have a function that return the reference of that 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've read somewhere that returning NULL is not part of clean code. So I was wondering what is the equivalent code for this case.

UPDATE: I've read this question and I think my case is different. In that case, if NULL is returned then do nothing, while I need to do something if NULL is returned

like image 479
jamesalone Avatar asked Apr 28 '15 11:04

jamesalone


People also ask

How do you stop returning null in Java?

Use Null Object Design Pattern Another way to avoid returning null is to use a Null object design pattern. A null object is an object without behavior like a stub that a developer can return to the caller instead of returning null value.

How do you avoid nulls?

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.

What to do instead of returning null?

Several alternatives for returning null values include using null object reference types, a null object pattern, and a result type as the return type. Therefore, the recommendation is to return an empty value instead of a null to keep the code clean and error-free.

How does Java handle null return value?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.


2 Answers

If you're using Java 8, consider the Optional class, but do note that it's not applicable everywhere.

Many think (me included) that Optional should be used only for return values, not parameters and especially not for object attributes. However as always there's no hard rule, just be careful that you don't replace null handling with Optional blindly, without understanding if you get any advantage from it.

In the example code for example, Optional won't do you any good. Since you perform some action regardless of null or not, you'll just be changing if(s == null) to if(s.isPresent()). However if the logic did something only if s is non-null, without an else you may be able to use Optional.ifPresent() to make things a bit cleaner. Of course there are other useful methods present in Optional that will give you cleaner code, such as the orElse() which can be used effectively for using default values.

like image 149
Kayaman Avatar answered Sep 19 '22 22:09

Kayaman


Looks like you mean the special case pattern (particular implementations are the Option or the Null Object pattern).

There are Java implementations of the Option type, named Optional, in Java 8 and in the Guava libraries.

In your case, you'll be using Optional<SomeObject> and having this implementation (I'm using the 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-explainable about returning an optional object. You would then 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
}
like image 37
ericbn Avatar answered Sep 19 '22 22:09

ericbn