Writing Honest Code

The idea of honest code is not anything new. We are all to some extent trying to be honest when coding. However, conditions arise that causes us to cut corners, and that is often when dishonesty seeps into the code. And once it is there, it tends to stick around.

Writing honest code is to focus on writing truly appropriate code that in itself reflects the expectations and requirements of the underlaying business logic.

This means that you try to always ensure your code actually tests what should be tested, even when testing against the inverted case would result in less verbose code. Select the data structures that best reflect the expectations and requirements of the project.

Honest code results in higher quality self-documenting code that is easier to maintain, and will likely cause less regression bugs. Writing honest code is to avoid anti-patterns. Everyone will benefit, through the entire lifespan of the project, as the business logic is easier to piece together when reading the code.

For example, if your mobile app never plays any sound without user interaction, then postponing the loading of sounds until after the view is shown results in more honest code. Anyone reading the code can now induce this simple fact.

Conversely, preparing the audio while views are still being initialized is less honest as nobody can actually assert any expectations about the use of sounds in the app. A result is that it’s not immediately clear if postponing audio preparation will cause issues or not.

If you use an optional boolean that is nil while no timer is running, and either true or false depending on the timer having reached a certain value, let the name of the variable reflect this. A suitable name could be something like nilOrHasReachedValue.

In short, honest code means to:

  1. Do things as late as feasible.
  2. Check what actually matters, not what is convenient.
  3. Put thought into naming things.
  4. Guard against entry requirements.

What do you think? Did I manage to explain the idea of writing honest code?

Leave a comment