Maps and Abstraction

The entire history of software engineering is that of the rise in levels of abstraction.
Grady Booch, The Limits of Software

That I was always a supporter of the idea that in object-oriented languages there is almost no place for switches is no surprise to those that know me.

A switch statement almost always can be replaced by a map of values, a map of commands or a state pattern making a cleaner code and more versatile, it is the object-oriented way of doing it.

I was even challenged on a class that I taught Java to software developers changing in to Java on this one, people said that there is occasions that it simply cannot be done, but none could come up with an example which I could not turn either into one of those three.

Some people will complain about those not being as optimal as switch, but then again Donald Knuth warned:

“Premature optimization is the root of all evil.”

First and foremost software developers should be concerned, when writing code with two things:

  • Is it correct?
  • Is it easily read and understand?

We write software for computers to run, but also for other human beings to read, for the human beings are the ones that maintain and add to the code, a computer language is not restricted to be a set of instructions to the computer, it is also the language that convey the meaning of the software to people who read it.

Code easy to understand is easier to optimize while a mess of optimization end up rewritten, or worse cut out. If the ones maintaining it can’t understand the code and it’s purpose.

That is not to say I never write switches, everyone has a lazy moment, yet it makes me feel that I have live butterflies in the stomach and usually I end up reworking the code to get rid of the pesky switches.

Lately I started to get the same from maps, every time I see a map I got that feeling that there is an abstraction that failed to be seem. After all, a map in its own nature denotes relationship among the entities mapped.

And the relationship asks for an entity to be born. A good example of that I extracted from a Java discussion list in LinkedIn, the guy asked a way to order a map by its values instead of keys and as some know usually what people ask is not what they need.

His problems were that he needed to sort cars by distance and he had a map from cars to distances that kept being updated. Here the source of his problem was that entity asking to be born, it was the key to solve the problem, once I modelled it for him as a Radar Blip and created a blip comparator that sorted the entries of a simple collection of blips by distance his problem was solved. (source code)

Leave a Reply

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

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

Facebook photo

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

Connecting to %s