Good quality code and TDD

Good quality code doesn’t happen by accident. It is intentional. It is the result of thousands of small decisions, each one shaping how easy our code is to read, test, compose, and change. We must choose between quick-and-dirty hacks, where we have no idea what edge cases are covered, and more robust approaches, where we are confident that no matter how the user misuses our code, it will work as expected. Every line of source code involves at least one of these decisions. That’s an awful lot of deciding that we have to do.

TDD process

Notice that we haven’t mentioned TDD so far. As we will see, TDD does not design our code for us. It doesn’t remove that essential engineering sensibility and creative input needed to turn requirements into code.

However, that does cause a lot of early failure with TDD, which is worth noting. Expecting to implement the TDD process and get good quality code out without our own design input will simply not work. TDD, as we will see, is a tool that allows us to get rapid feedback on these design decisions. We can change our mind and adapt while the code is still cheap and quick to change but they are still our design decisions that are playing out. What is good code? What are we aiming for?

Readability

Good code is all about readability. We optimize for clarity. We want to be kind to our future self and our long-suffering colleagues by engineering code that is clear and safe to work with. We want to create clear and simple code that is free of hidden traps. While there is a huge range of advice on what makes good code, the basics are straightforward:

  • Say what you mean, mean what you say.

  • Take care of the details in private.

  • Avoid accidental complexity.

Say what you mean, mean what you say

Here’s an interesting experiment. Take a piece of source code (in any language) and strip out everything that is not part of the language specification, then see if we can figure out what it does. To make things really stand out, we will replace all method names and variable identifiers with the symbol ???. Here’s a quick example:

Get hands-on with 1200+ tech skills courses.