Principle of least surprise

Another Principle! I am on a roll! Although, to be honest, this is not an actual principle.

If you work for a serious company, you would most likely have one of these printed out and hanging from one of your office’s walls. If you don’t have it, now you have something to do today.


When it comes to source code, this principle can be summarised as:

Don’t try to be a smartass. Write code that is easy to understand.

Oh, noes! Is this another rant about semantic code?

Actually, no, it is not, thanks for asking. I would not say it is a rant, I would say it is a more like unwanted advice, but about something else.

The offending code.

This code, slightly edited to protect the innocent, was extracted from an actual codebase my team has to maintain.

There are plenty of WTFs here. But the one that stands out the most is on smartMethod: why on earth would I loop all the entries in a Map only to act upon those that match a set of constant, immutable, known keys?

Isn’t our life complicated enough, as it is? Why do we want to make our code more difficult to read and understand, for the shake of a flexibility that may or might not be necessary? A flexibility that, at least in this example, is not even flexibility at all?

Do the simple thing first.

Instead of looping the map keys looking for something we already know is there… why not just ask for it?


Now, if you look at that code carefully, if you look at any piece of simple, dumb code, carefully, you will instantly hear it screaming at you, shouting everything is wrong with itself.

In this example, the smartMethod has an expectation on which keys in a Map it will need to use. That tells you that a Map is not the right type for that parameter: maybe two strings would do?


Keep it simple. Do not try to impress anyone. Seriously, your skills as developer are not directly proportional to how obscure your code is.

Leave a Reply

Your email address will not be published. Required fields are marked *