21 November 2007

On the Samurai Principle

Some blogs recently pondered on the Samurai Principle. It made me think, because I'm one of the many "guilty" of returning None/null rather than raising an exception. To me, it happens more often when working with Python rather than Java, because it's very natural to write "if something_not_found: return None". Also, abusing exceptions can end up polluting your code with dozens of nested try-catch/except, which kill readability and tend to be much worse than a simple "if (obj is None):".

This said, I agree that NullPointerExceptions are a royal pain, and "AttributeError: 'NoneType' object has no attribute 'something' " is equally bad to deal with. API programmers in particular should try hard to return this sort of stuff as little as possible.

I guess the bottom line is that in medium stat virtus, as it's often the case with these "absolute principles of programming"; at the end of the day, when we program we are applying science, not demonstrating it. And as much as we love them, samurai lost all their wars ;)

3 comments:

Cristian said...

Actually i hate Samurais AND Exceptions :)

David Boddie said...

One of your own earlier entries about Partner Programmes references a Joel Spolsky article that also talks about this issue:

http://bakerstreetsystems.blogspot.com/2007/10/empowering-programs.html

However, that article was written back in 2003. It's funny how history repeats itself.

GiacomoL said...

Eh, it's probably because the debate is still all but settled... Unfortunately, it's impossible to settle it in these "black or white" terms, when a mixed approach is clearly the way to go (as long as your APIs are documented with a big red blinking "CAN RETURN NONE" statement).