“For” hack with Option monad in Java
Published August 6th, 2008 in Haskell, Java, Maybe, Monad, Null, Option, ScalaThere 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.
20 Responses to ““For” hack with Option monad in Java”
- 1 Pingback on Aug 8th, 2008 at 9:33 am
- 2 Pingback on Oct 9th, 2008 at 4:55 pm
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.
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
forand 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 clientforloop 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
forhack 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.
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 :)
@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.
Why is
for (String name: option) {
// do something with name
}
better than
if (name != null) {
// do something with name
}
Excellent post. And scary, I did exactly the same in my “Optional” class yesterday…
@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”.
@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” :-)
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;
}
“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.
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.
Nice!
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…
@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.