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

4
  • possible duplicate of Avoiding "!= null" statements in Java? Commented Apr 28, 2015 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) Commented Apr 28, 2015 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 Commented Apr 28, 2015 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? Commented Apr 28, 2015 at 11:33

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think is worth mentioning Guava's Optional too...
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 } 

Comments

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

1 Comment

@ericbn And I also provided what he should do (also implement hasSomeObject())
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.

3 Comments

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?
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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.