How to write good code

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Overview

Notes on how to write good code

What is good code?

If you don't know what the goal is, you can't reach it. You need a measuring stick for good code.

My heuristics:

  • Good code is readable. Someone unfamiliar with the software or even the language will be able to figure it out.
  • Good code is concise. It does one thing, and does it well. It is clear about its goals and intents and can be part of a larger ecosystem of software.
  • Good code is useful as-is. It can be extended or embedded.
  • Good code is stable. As it grows and evolves, it doesn't change substantially.

How to get good code

  • Think hard about what the code needs to do. Understand the Unix Philosophy and use it.
  • Keep the coupling between this code and other code very, very loose. See Loose Coupling.
  • Don't be smart. Try to make the code as simple as possible. If the code can't be simplified, document it furiously.
  • Backwards compatibility. Every change you should make should be backwards compatible. If you think about it hard enough, you will always find a way forwards without breaking backwards compatibility.

Bad code smell

  • Code changes a lot. (Did we not understand what it needs to do in the first place?)
  • Code is brittle, and doesn't work outside of its one or two intended purposes. (Maybe we didn't generalize the problem or we don't understand loose coupling.)
  • Code has a lot of different things all together. This is a sign that you are growing an operating system. Don't do that!
  • Versioning issues. This is because you didn't think about backwards compatibility.
  • Code depends on bad code. The thing about code odors is they permeate all the way to the user.