Friday, April 8, 2011

Null considered harmful?

So I subscribed to Gary Bernhardt's Destroy All Software screencasts. I've only watched the demo one ("How and why to avoid nil"), but I think it's pretty good! (disclaimer: I know him IRL; un-disclaimer: he's very good at software; in conclusion, you ought to subscribe too)

The message is pretty simple: avoid nil/null. And I dig the justification: someday you'll get a traceback that says NullPointerException (forgive me for translating to Java; I used to work for a big company), which tells you where someone tried to dereference null, but it doesn't tell you where the null came from.

But that frustrates me! In a lot of cases, null makes sense. For example, if you're getting something from a map. If "foo" is not a key in your map, map.get("foo") should return null! Otherwise, if map.get("foo") throws an exception, you have to do all this gross exception handling. And not only is it gross, but you're using exceptions for control flow, which is a Big No-No.

Or, okay okay, I'm learning python, you always say:
if "foo" in map:
  map["foo"]
Seems uglier than it needs to be. You're asking for "the value that corresponds with foo" and sometimes there is none.

Nevertheless, I've heard the null pointer referred to as a terrible idea; for example, here. So I'd like to try writing a whole project without nulls and see what happens.

2 comments:

  1. In Python, you can say map.get('foo', some_default_value), which almost always makes sense. When it doesn't, I usually do:

    try: return map['foo']
    except: handle exceptional case

    (This would be four lines in actual code; Blogger sadly rejects the code tag.)

    "Exceptions for control flow" is another issue, and I'm pretty sure that tomorrow's DAS screencast will be about it. :)

    ReplyDelete
  2. I imagine you're right. I guess you're saying: code that calls map.get('foo') should deal with the case where 'foo' is not a key in the map; it shouldn't just let the null percolate up. I can buy that, at least until I can come up with a good counterexample.

    ReplyDelete

Note: Only a member of this blog may post a comment.