by Leon Rosenshein

Code Virtues

I’ve talked about code smells before. Just the other day I talked about comments as a smell. What about the opposite? Are there code virtues?

Of course there are. Things that we want our code to have. In fact, the Pragmatic Programmers published a list back in 2011

Because English is a slippery language and, as Humpty Dumpty said, words can mean what we choose them to mean, each virtue is given as not only what it is, but what it isn’t. It gives you a continuum so you can tell what to avoid as well as what to move toward.

There are lots of details in the article, but touching briefly on each of the virtues:

Working: as opposed to incomplete

Straight from the Agile Manifesto, code needs to work. If it ain’t done, it isn’t adding value, and doesn’t have much virtue.

Unique: as opposed to duplicated

Is it DRY (Don’t Repeat Yourself)? Only have one way to do something. If you need to change something, have it in one place. This goes beyond constants and functions. Keep your domains clean and respect their boundaries.

Simple: as opposed to complicated

Be straightforward. Following on from Unique, have decisions made in one place. Have functions do one thing. Process collections instead of multiple individual items.

Clear: as opposed to puzzling

This one is a bit harder. I would have said Clear, as opposed to clever. Avoid neat tricks. Don’t surprise the reader with side effects. As John Scalzi once said, the failure mode of clever is a**hole.

Easy: as opposed to difficult

Don’t make things hard on yourself. For example, when you go from doing one thing to doing two, it makes sense to just add an if/else. When you add the third, that might still make sense. After that, some kind of table or data driven approach makes more sense. Another thing that makes things easy is automation. Once you figure out how to do something, automate it. It’s easier, and it’s harder to get it wrong.

Developed: as opposed to primitive

One of the big things we do when programming is deal with complexity. There’s some level of complexity you can’t get out of the system. What you can do is make sure the complexity is in the right place and covered with the appropriate abstractions. If your domains are set up correctly, you can use the domain and never need to deal with their internal complexity.

Brief: as opposed to chatty

Be succinct. For whatever succinct means in the language you’re using. Be idiomatic. Those conventions are shared for a reason. It makes your code easier to read and understand.

Now go forth and write virtuous code.