7

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

Community
  • 1
  • 1
jamesalone
  • 301
  • 1
  • 6
  • 19
  • possible duplicate of [Avoiding "!= null" statements in Java?](http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java) – sheltem Apr 28 '15 at 11:23
  • 1
    As aside note to the answers - this is not C#, method names in java should start with lower case letter (very strong java convention) – amit Apr 28 '15 at 11:29
  • from what I read at the solution in that question, I think that question is more like do nothing if null is found, while I need to do some action if null is returned. @amit oh okay, thanks for reminding me – jamesalone Apr 28 '15 at 11:33
  • Could someone give an example of the use of Optional in the context of his example? His function returns an Object, in the example it's possible the Object is not in the list, which means he either returns null, or throws an exception. How would this problem be solved using Optional? – JohannisK Apr 28 '15 at 11:33

4 Answers4

6

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • 1
    I think is worth mentioning [Guava's Optional](https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained) too... – ericbn Apr 28 '15 at 11:56
5

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
}
ericbn
  • 10,163
  • 3
  • 47
  • 55
1

You can throw NoSuchElementException, this goes well with the methadology of "fail fast".

However, if your code is starting 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 element does not exist, only if your API also supports contains() (or HasSomeObject(obj)) method.


Disclaimer: This answer fits for prior to java-8 code, for java8, a better practice will probably be Optional, as suggested by @Kayman

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333
1

One common approach that you could consider is the Null Object Pattern.

Rather than returning a NULL, you return an instance of the correct object type, that just does nothing when you call its methods. It doesn't fit in all cases, but its worth thinking about.

DaveH
  • 7,187
  • 5
  • 32
  • 53
  • Well, I've read that just a moment ago, but what if I want to do something when the object in that list is not found? – jamesalone Apr 28 '15 at 11:36
  • This really depends on what it is you want to do. If the code takes a completely different path then this pattern probably isn't what you want. What ( briefly ) will happen in each case ( object found vs object not found ) in your example? – DaveH Apr 28 '15 at 12:02
  • I'm trying to filter a list depends on the object is found or not. If the object is found, it filters based on the properties of the object, while if not found, it filters differently. – jamesalone Apr 28 '15 at 12:37