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


  1. Posted Nov 6, 2009 at 8:46 pm | Permalink

    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. Michael Schlösser
    Posted Nov 6, 2009 at 9:13 pm | Permalink

    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:

  3. Posted Nov 6, 2009 at 9:25 pm | Permalink

    I think this will be interesting for you :)

  4. Macaca
    Posted Nov 6, 2009 at 10:20 pm | Permalink

    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. Posted Nov 6, 2009 at 10:36 pm | Permalink

    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.


  6. Posted Nov 6, 2009 at 11:17 pm | Permalink

    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. Posted Nov 6, 2009 at 11:43 pm | Permalink

    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. Posted Nov 7, 2009 at 12:32 am | Permalink

    There’s an open issue for the request of true generic types in AS3 found here:

  9. Alan
    Posted Nov 8, 2009 at 8:09 pm | Permalink

    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:

    var user = getUser(id: String);
    Alert(“No User Exists”);

    Anyone’s thoughts…..

  10. Posted Nov 22, 2009 at 9:13 pm | Permalink

    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 {
    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)

  11. amn
    Posted Jan 21, 2010 at 3:24 pm | Permalink

    Nicolas, I would have to say that what you propose, relies on “non-polymorphism” approach again, just as checking for ‘null’ values does, because you have to switch between the type of object you get. I think, in that case it may be just as attractive to stick to the old methods.

    I consider the following equally viable and maintainable as your example, if you disagree you are welcome to state your reasons:

    /// Code happens to be in haXe

    var user = get_user(id);
    if(user == null) /* handle error */;

    /* ... */

    Joas approach however is closer to true polymorphism, because the context of obtaining a user object reference does not to know the type of returned value and explicitly account for the ‘user not found’ error – it always returns an object expected to be able to be called ‘isLoggedIn’ on, even for users that do not exist.

    In my opinion however, it is an abstraction that is not really necessary. I do acknowledge its need for readable code, but I do not consider ‘null’ values that bad. Null is just a special value that indicates error condition, just as None or Some types are, but in case with the latter, they have to define the ‘isLoggedIn’ method which frankly makes no sense for users that do not exist. I value semantics over code readability.

  12. amn
    Posted Jan 21, 2010 at 3:35 pm | Permalink

    Also in case with Joas approach, it becomes an impossibility for the context to differentiate between users that do not exist and users not logged in. Sometimes such information can be valuable, f.e. when optimizing backends – so that these do not go the extra mile with database accesses after it is already been established that no such user even exists.

    The difference between the invalid and offline users has been abstracted into the body of ‘get_user’ method, and so the context keeps running logic that assumes user exists, when in fact he does not. I would say, if there is a need for code that needs fewest lines to do what it does, simply make ‘get_user’ old-fashioned (return null on invalid users) and call it in turn from another abstraction context, something like an ‘if_logged_in’ procedure which will trace the ‘Hooray’. Just as readable, but arguable more optimized.

    function get_user(id): IUser
    // return an IUser or null when no user by given id

    function cheer_if_user_logged_in(var id)
    var user = get_user(id);
    if(user == null) return;
    if(user.isLoggedIn) trace(‘Hooray!’);

    cheer_if_user_logged_in(); //An abstraction for a very specific case

  13. Posted Jan 22, 2010 at 3:26 pm | Permalink

    amn: I do not think you are quite right about that. First of all, if the method signature for getUser is “getUser(name: String): User” you expect that you get a user from it.
    You have no idea that it might return null. Basically, whenever you dereference the pointer to an object that is the result of a method, you have to check for null. If the signatrue is however “getUser(name: String): Option[User]” you immediately know that the result is only optional. This means you have to expect the case that you do not get a result.
    The model Nicolas proposed is the classical way from functional languages and I would also favour it, but it is not possible to write such code in AS3 since we lack parameterized types.

    Regarding your last argument, you could easily check in the proposed AS3 version if the User object is the EmptyUser or the NullUser if you are interested in that information. This information is not lost.

    Basically, the idea is to get rid of null since it makes it cumbersome and error prone to write code. The Scala compiler would also warn you for instance if your match is not exhaustive on the Option[T] and this makes it an even better feature.

    If you do not consider null values that bad, check out the link from Maxim :)

3 Trackbacks

  1. […] This post was mentioned on Twitter by Joseph Burchett and joa ebert, Joseph Burchett. Joseph Burchett said: RT @joa: New blog post: Getting Rid of null […]

  2. By uberVU - social comments on Nov 6, 2009 at 8:51 pm

    Social comments and analytics for this post…

    This post was mentioned on Twitter by retrogamer4ever: RT @joa: New blog post: Getting Rid of null

  3. […] この記事を読んでいて、「条件つきコンパイル」というキーワードにぶつかったので、メモ。 […]