Getting Rid Of null

A couple of weeks ago I started learning Scala. I can highly recommend it. The language has a lot of great approaches to multithreading and scalability. The reason why I like Scala is because it is so simple yet powerful.

Of course doing something at home influences work. I decided to write a build tool for the Hobnox AudioTool which is about 200 lines of Scala code. Cool thing is that this tool replaces a manually maintained Ant build and all project dependencies are always correct. Plus analyzing the dependencies in a more powerful way allows me to spawn the compiler in parallel. Building the AudioTool is now twice as fast and much more comfortable.

When learning a new programming language you also learn about new concepts. Functional languages in general have a different approach to nullable types. I know Scala is not the only one but let me introduce the concept in terms of ActionScript.

When you have a method that returns either a result or nothing: what do you do? Imagine you have some kind of service and a Dictionary of users. Requesting a user works by his unique id. The Dictionary is private to the class since you want to keep it read only.

function getUser(id: String): User {
  return hasUser(id) ? users[id] : null;
}

If I would now simply ask the service for an unknown user and do something like if(getUser('xyz').isLoggedIn) { trace('Hooray'); } I could probably and up with a null-reference error. No one checks for me if the user exists. So what else could we do? Write a lot of boilerplate code and prepend a check if the user is null or not each time we request one from the service. A much better approach in my opinion is to throw an error as early as possible. In this case we would rewrite the method to something like this:

function getUser(id: String): User {
  if(hasUser(id)) return users[id];
  throw new NoSuchUserError(id);
}

In this scenario we get informed about the error as early as possible. But we are stuck again. First of all ActionScript does not enforce you to catch possible exceptions. This means if you do not read the documentation of a method carefully or look into the source code of a method before calling it somewhere you will never know that it throws an exception. And what if we are actually in a scenario where we do not expect errors for non-existing objects? Think of the Dictionary object throwing each time an error when you access it and the result is null. How could I even check if an object exists in a Dictionary?

try {
  dictionary[key];
  return true;
}
catch(noSuchElementError: NoSuchElementError) {
  return false;
}

I guess you see that this can not be the solution to our problem. In a real world example you may deal with your own collection of objects instead of a Dictionary of course. So we have to get rid of exceptions and null for the optimal solution. Scala’s approach to this problem is the Option type. We always abuse null as a placeholder when we want to express that an element does not exist. The Option means that either Some or None result exists. Rewriting our getUser function using this approach would yield the following ActionScript code.

function getUser(id: String): Option {
  return hasUser(id) ? new Some(user[id]) : new None();
}

Why is this much better than the old approach? When calling the method you will always know that the method has only an optional result value. We get rid of the exception and null values. Our only problem at the moment is ActionScript. The result is now untyped. In an ideal world this method would be written as:

function getUser(id: String): Option.<User> {
  return hasUser(id) ? new Some.<User>(user[id]) : new None.<User>();
}

However we can still tackle this issue by implementing null-representations of our objects. Imagine the User class. You could rewrite the code to something like this.

function getUser(id: String): IUser {
  return hasUser(id) ? user[id] : new NullUser();
}

final class NullUser implements IUser {
  public function get isLoggedIn(): Boolean { return false; }
  public function get name(): String { return 'null'; }
}

And even if you are interested in null-reference errors you could rewrite your code to something like this:

final class NullUser implements IUser {
  public function get isLoggedIn(): Boolean {
    CONFIG::ThrowNullReferenceErrors { throw new NullReferenceError(); }
    return false;
  }
  public function get name(): String {
    CONFIG:: ThrowNullReferenceErrors { throw new NullReferenceError(); }
    return 'null';
  }
}

It is definitely a very different approach. A functional language like Scala allows you to deal much better with Options. But it makes sense to diferentiate between an uninitialized variable which is null and an optional result of a function. Unfortunately this is at the moment very painful with the lack of generics in ActionScript.

Related Posts

13 Responses to “Getting Rid Of null”


  1. 1 Troy Gilbert

    I like the idea of create custom “null” values for custom types. It makes for some pretty slick API’s, though it obviously takes more work to build out the API.

    In the case above, I would not create a custom Null class, because from my perspective it’s not a “class” of user or a new type. Rather, I’d create a null-valued user, i.e. User.NULL (which may in turn get its value from a NullClass like you showed).

    Semantically, null is a object-reference value (just like 0 is a Number value or “” is a String value). For many custom types (classes), there are semantic “nulls” or “undefined” that should be provided by a complete API.

    Thanks for the info on Scala… really need to dive into a functional language these days… it’s been years!

  2. 2 Michael Schlösser

    Just as an addition to your blog entry: the described approach of returning an (empty) object that conforms to a specific interface (in your example IUser) is know as the “Null Object Pattern” and/or the “Special Case Pattern”.
    Fowler describes this concept/pattern in his book “Patterns of Enterprise Application Architecture” very well.

    Further reading:
    http://martinfowler.com/eaaCatalog/specialCase.html
    http://en.wikipedia.org/wiki/Null_Object_pattern

  3. 3 Maxim Zaks
  4. 4 Macaca

    Nice concept, worth looking into.

    On generics: FDT templates work to some extent if you establish a good convention (but oc they just generate source code).

  5. 5 James Ward

    Hey Joa,

    Great post! Want to port Scala to run on Flash Player? I talked with Martin Odersky about this a year ago. He said it’s certainly possible he just doesn’t have the time. Scala on both sides of the wire! That would be very cool.

    -James

  6. 6 joa

    Troy: I agree and in Scala, None is also an “object” and not a “class”. It is Scala’s concept of singletons.

    Maxim: Thank you for the link!

    Macaca: True, you can generate a lot of files but your SWF will get bigger and bigger. Besides, what if you figured out that you have a bug in your template? :)

    James: I have had a look into the compiler. I am highly interested on getting Scala running inside the Flash Player and would be willing to invest time. That would be spring next year and definitely after Scala 2.8 has been released.

  7. 7 Jackson Dunstan

    I’ve heard of languages like Scala without a null type, but haven’t gotten around to learning any of them. I think your null solution (including debug-only exceptions) could be pretty nice, although seems like a lot of code to write and maintain (as you point out). It also seems like it could slow down the program if used widely, as you pointed out on my site and bloat up the SWF as you pointed out above in the comments. Perhaps a tool could be created that would create and update these “Null” classes. That might at least help with the headache of creating and maintaining the Null classes. I’m not sure what to do about the speed…

    Thanks for the article!

  8. 8 TK

    There’s an open issue for the request of true generic types in AS3 found here:
    http://bugs.adobe.com/jira/browse/FP-811

  9. 9 Alan

    Joa,
    Right now, I’m in the camp of ‘Conditionals are not (mostly) needed in OOP’.

    I would ask, why would a developer design their application in a manner that allows a situation where nulls pop up?

    In the example accessor, getUser(id: String), I’d argue: Why is an invalid ‘id’ being passed in?

    If you do have a design whereby the developer can’t control what
    ‘id’ is being passed, I’d suggest this:

    if(isValidID(id))
    {
    var user = getUser(id: String);
    passUserToClientObject(user);
    }
    else
    {
    Alert(”No User Exists”);
    }

    Anyone’s thoughts…..

  10. 10 Nicolas

    This is something that comes from functional languages such as OCaml, where there is no null and where pattern matching is used to differentiate between None and Some value

    You can actually do the same in haXe :

    enum Option {
    None;
    Some( v : T );
    }

    var x = None;
    var y : Option = Some(56);

    switch( opt ) {
    case None: // handle the “null” case
    case Some(v): // “v” is the actual value (not null)
    }

  1. 1 Tweets that mention Getting Rid Of null at blog.joa-ebert.com – Blog of Joa Ebert -- Topsy.com
  2. 2 uberVU - social comments
  3. 3 djakarta-trap - [CS4]条件つきコンパイルのメモ。

Leave a Reply