the blog for developers

“For” hack with Option monad in Java

There has been some discussion going on in the blogosphere about monads, and especially about the Haskell Maybe monad or the Scala option class. Those are ways to prevent problems with NULL and NPEs that Java lacks. Java returns NULL form many methods to indicate failure or no result. Suppose we have a method which returns a name:

String name = getName("hello");
int length = name.length();

The problem with this method is that we don’t know if it returns null. So the developers needs to deal with length == null, though the compiler doesn’t force the developer to deal with the returned NULL. A lazy developer then leads to null pointer exceptions. Other languages deal in different ways with this problem. Groovy has safe operators and Nice has option types.

Some posts like the one from James show how to use options in Java. All have the problem that you need to unwrap the value inside the option / maybe. Scala ans Haskell do that automatically for you, with the case classes in Scala for example.

But there is a construct with syntactic sugar in Java which unwraps the value from inside another class: the for loop from Java 1.5.

Option[String] option = getName("hello");

for (String name: option) {
	// do something with name
}

To make this work we need our option class to implement Iterable.

public abstract class Option[T] implements Iterable[T] {
}

And the None and Some sub classes to return an empty iterator

public abstract class None[T] extends Option[T] {
  public Itertator[T] iterator() { return EMPTY_ITERATOR; }
}

or an iterator with one item.

public abstract class Some[T] extends Option[T] {
  public Itertator[T] iterator() {
    // or better use google-collections
    List[T] list = new ArrayList[T]();
    list.add(this.value);
    return list.iterator();
}

Then voila Java does the unwrapping for us and instead of

Option[String] option = getName("hello");
if (option instance of Some) {
    String name = ((Some) option).value();
} else { ... }

we can write (sacrificing the else):

for (String name: getName("hello")) {
	// do something with name
}

Thanks for listening.

Update: Completely ignoring the point of this post, Euxx posted a correction for the single element list creation I did.

  return Collections.singletonList(this.value).iterator();

Happens all the time in IT, people missing the point but nitpicking on something irrelevant. Other than that, if we start arguing performance, “The java.util.Collections class also have number of other utility methods that allow to shorten code like this and help to improve performance of your application.” I’d write (or reuse) a OneElementIterator something like this (could probably be optimized with some further thinking)

public class OneElementIterator[T] implements Iterator[T] {

	private boolean done = false;
	private T element;

	public OneElementIterator(T element) {
		this.element = element;
	}
	public boolean hasNext() {
		return ! done;
	}
	public T next() {
		done = true;
		return element;
	}
	public void remove() {
		// not supported, throw exception;
	}
}

(Or again using google collections)

“I can’t not notice the ugly use of ArrayList to create collection with a single element, but what made matter worse, is that author suggested to use 3rd party library to replace those 3 lines of code.”

As far as I know, the JDK does not help you very much with Iterators or Iterables as third party libraries do. So, yes, I’d suggest using a third party library to implement an Iterator/Iterable for Option.

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.
Leave a reply.

Comments

James

And then you return 2 names from the getName method and you a buggered…

I think this for loop would just confuse me in a months time, not to mention my collegues.

stephan

No, on the contrary:

“And then you return 2 names from the getName method and you a buggered…”

The return type of the getName() is Option[T], so you can’t return more than one without changing the signature.

In the case that you don’t declare the return type in your client code:

a.) If your code handles 0 or 1 return values (None/Some) with a for and does something, like add the name to an index, or add the name to a cache, or validate the name, then your logic also works for more than one name. And you don’t need to change the client for loop of your code.

b.) If you need to handle 0 and 1 and n in different ways (what most often you don’t), then the for hack isn’t suitable of course.

“I think this for loop would just confuse me in a months time, [...]“

Not if you think of an Option as a 0..1 element container.

You already have that class in Java libs, it’s called Collection. Just use a Collection[String] instead of Option[String] and not have to code two additional classes.

// NULL name
Collection name = Collections.emptySet();

// Value
Collection name = Collections.singletonSet(“Joe”);

for (String n : name) {
// Do something
}

IMHO… Not a good idiom. It’s to much work to prevent NPE and would confuse whoever needs to maintain code.

Cedric

Cute hack, Stephan :-)

The main point of Monads is the way you can combine them. E.g. in Haskell the point of “do” is not just that you don’t have to handle empty cases, but that you can have a succession of operations returning empty that you can handle seamlessly. I do like where you’re going, though :)

stephan

@Vjekoslav: While Option can be seen as a 0..1 container, the reverse isn’t true. A Collection is not a Maybe/option.

@Cedric: Thanks. From an unrelated post “Others I’d like to meet are above all Crazy Bob for Dynaop (and Guice), Cedric for his stand on dynamic languages and Rickard of course.” ;-)

@Jevgeni: Yes, of course your’re right. That wasn’t the focus of this point. While this isn’t that powerful for Option, combination and mapping is very powerful for Either.

BoD

Why is

for (String name: option) {
// do something with name
}

better than

if (name != null) {
// do something with name
}

Kieron Wilkinson

Excellent post. And scary, I did exactly the same in my “Optional” class yesterday…

stephan

@Kieron: Thanks. And I’m scared too :-) At least it shows that I’m not crazy … or the only one.

@BoD: a.) The developer has to deal with the None case, with NULL he can just ignore it b.) The developer knows there is a None case, with NULL he can’t see it in the method signature. And see the linked posts: NULL can mean lots of things (error, no result, etc.), None is much better.

For the record, the James mentioned in the article is me but the James who was “buggered” up there is not :-)

I have to say, it’s a nice hack.

Another way to deal with Option/Maybe in Java is to use the visitor pattern. I wrote a quick one for Tony Morris and he used it in a presentation on Scala (where he called it OneOrNone). The relevant slides are at

http://projects.workingmouse.com/public/intro-to-highlevel-programming-with-scala/artifacts/latest/chunk-html/ar01s08s02.html

and

http://projects.workingmouse.com/public/intro-to-highlevel-programming-with-scala/artifacts/latest/chunk-html/ar01s08s03.html

However, as Jevgeni points out, the real nifty bit about Option/Maybe as a monad is composibility. E.g. in Scala

val maybeSum = for {
x <- someMaybe
y <- someOtherMaybe
} yield x + y

or Haskell

let maybeSum = do
x <- someMaybe
y <- someOtherMaybe
return x + y

The iterator trick in Java, by contrast, yields the following

Option[Integer] maybeSum = new None[Integer]();
for (x:someMaybe) {
for(y:someOtherMaybe) {
maybeSum = new Some(x + y);
}
}

Still, that’s much nicer than the manual instanceof/extraction I had and a bit nicer than using a bunch of nested visitors. Hats off!

[Ed: Added + see next comment]

My pluses got eaten in the previous comment. Everywhere you see “x y” read “x plus y”.

stephan

@James: Thanks a lot.

The double loop is a nice construct. Hats off for thinking of that and the anology to Scala and Haskell with for and do. Especially “for” :-)

[...] Productivity in software development « “For” hack with Option monad in Java [...]

Jeez, this double loop construct is so much better than

if (x != null && y != null) {
return x y;
}

…and much more readable.

Perhaps you should use try to some patterns that are better fit
for Java like Visitor mentioned by James or Null object. Search
for design partners or GoF.

Don’t get me wrong, monads are cool but can’t be expressed
in Java at this time. Perhaps if Java7 incorporates closure
proposal, we’ll be able to express something like:

withObjectsThatArentNull(x, y) {
return x y;
}

stephan

“Perhaps you should use try to some patterns that are better fit
for Java like Visitor mentioned by James or Null object.”

I’ve read the GoF Book 15 years ago, taught them to lots of students and used them in lots of projects. I think the Null object (though not from the GoF book but from Fowler several years later) is used not often enough. Recently I introduced NullId to a project (with a nice isValid() method) with very good results. More people should do that.

“Search for design partners or GoF.”

Search for Refactoring and Fowler for the Null object pattern.

Nonetheless Option/Maybe is something different.

lqd

Where i find this could also work is in adapter patterns (see Tim Boudreau’s last blog about API and ‘Capability pattern’ or Eclipse getAdapter/IAdaptable API)

for (CapabilityClass17 cap : getAdapter (CapabilityClass17.class)) {
// do something with the extended API
}

Ironically, if you think your class had to behave like a list, and you add that adapter later, you could actually get some kind of real looking for loop :)

for (Object s : getAdapter (List.class)) {
// Booya :)
}

As for the type of the iterator, maybe super type tokens can help.

stephan

Nice!

3bit

Am i completely crazy or is the Type Parameter in Java not usually enclosed in ”? Or is there a deeper meaning behind this? Since I didn’t trust myself I tried this code in Java but it would give me errors because of the misplaced array ‘[' ']‘ qualifiers…

stephan

@3bit: You’re right. But lots of people use [] in blogs and wikis because they are easier to use with most blogging software than pointy braces.

[...] et al. Null-Handling in Scala using the Option-Type seems so interesting that some people try to carry it over to Java as an alternative to Null-Objects or null checks. The rich collection classes and [...]

Leave a Reply

What people wrote somewhere else:

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?