Bad Coding Habit: Append Needless Words to Classes

This is a short opinion piece about a very good talk I’ve been watching recently. It was presented by Kevlin Henney and is about seven ineffective coding habits of many programmers. Not only is his style very engaging and entertaining, it also contains seven informational things a coder might want to think about. While I generally agree with all of it, there’s one instance where I can see why it is done – if that’s the actual reason is a question for another day. I’m talking about appending the word Exception to classes that are exceptions.

The part of the video starts at 31m and 42s. What he’s basically saying is that adding Exception to an exception is only redundant. It doesn’t do any additional good. In fact, it only adds noise to the code. Especially, if you consider that exceptions are always accompanied by very specific keywords, namely throw or catch. There simply is no reason to add Exception to the class name as it should be immediately obvious from the code. Apart from a few examples of rather terrible names, most exceptions would even transport the desired meaning without the name affix.

And while that is true, I think it’s a bit odd. Maybe that’s just years of bad habit – well, that’s what the talk is about – but there’s one thing to it. Example time.

throw new IllegalArgument();
catch (IllegalArgument e) { … }

As already said, it’s obvious what’s going on. But from only reading the words I tend to wonder what I am dealing with here. Am I throwing the illegal argument, the reason for the exception? Am I catching an illegal argument? Is this the argument that was illegal? Just read the words “catch illegal argument”. Sounds like somebody is throwing me an argument that is deemed inappropriate for whatever task, not an exception notifying me about the fact that there was a thing that should not be.

Do you see what I’m getting at here? If, instead, you take the verbose road and append Exception then there’s no way this can be misinterpreted.

throw new IllegalArgumentException();
catch (IllegalArgumentException e) { … }

And isn’t that what we want? Unambiguous code? It’s definitely more to read, but it’s also a bit more obvious in this context. I think. But again, just a bad habit?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.