About Me

I am a computer programmer. I do programming professionally and for a laugh.

Technical stuff on programming, java, DSLs, etc...

Wednesday 31 August 2011

null - the epic Java fail

One of the greatest fails in programming history is the invention (and inclusion in java) of null. What is null? A concept borrowed from c, with a meaning like an uninitialised pointer.

But hey, there are no explicit pointers in Java? Anyways, it kind of means that you have, or will in the future have, an object that may or may not be there. Or a method returns an object but it may not. Below is a concept I borrowed from Scala that better reflects optionality.

public void doStuff() {
      // returnAStringOrNot returns Some<String> or None
      Option<String> aStringOrNot = returnAStringOrNot();
      if (aStringOrNot.none()) {
            doSomeOtherStuff();
      } else {
            String aString = aStringOrNot.get();
            doSomeGoodStuff(aString);
      }
      //or similarly
      for (String aString : returnAStringOrNot()) {
            doSomeGoodStuff(aString);
      }
}
private Option<String> returnAStringOrNot() {
   return inAGoodDay ? Option.Some("Hello") : Option.<String> None();
}





2 comments:

  1. But what happens if returnAStringOrNot() returns a null?

    ReplyDelete
  2. @Genius:- you get a NullPointerException when you call none() or get() Genius

    ReplyDelete

Followers