Tips for keeping your code clean

In this post, I’ll be sharing clean coding conventions recommended by Robert C. Martin in his video series on “Clean Code”.

Clean code reads like well-written prose.

Grady Booch

Names

  • If a comment is required to explain what a variable does, it has a bad name.
  • If you have to examine the code that a function executes to understand what it does, it has a bad name.
  • All names should be pronounceable.
  • Avoid naming things with prefixes and mysterious encodings.
  • Variable name lengths should be directly proportional to the size of their scope.
  • Class name lengths should be inversely proportional to the size of their scope.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler

Functions

  • The first rule of functions is that they’re small. The second rule is that they’re smaller than that.
  • Small functions act as sign posts helping people navigate your code.
  • Classes and structs hide in long functions.
  • Functions should do one thing. If you can extract one function out of another, you know it’s doing more than one thing.
  • Extract until you drop!

Redundant comments are just places to collect lies and misinformation.

Robert C. Martin

Function Structure

  • Function signatures should be short. A good rule is to have no more than 3 arguments.
  • Booleans and potentially null arguments should not be passed into a function. There should be separate functions that handle each case.
  • Public functions should be at the top of a chain of private functions where each function only calls functions that are below them.
  • Switch statements are a missed opportunity to use polymorphism and also interfere with the principle of independent deployability.
  • Functions that return a value should not change state. Functions that change state should not return a value.
  • It’s better to throw an exception than to return an error value.

I’m not a great programmer; I’m just a good programmer with great habits.

Kent Beck

Form

  • Comments should be rare. Every comment is a failure to properly express yourself in code.
  • Keep file sizes small.
  • Manage line lengths so you never have to scroll to the right.
  • Methods of a class should hide data, not expose it. If they must expose data, they should do it in the most abstract form possible.
  • Know the difference between classes and data structures. Classes have private variables and public methods. Data structures have public variables and no methods.

Every time I see commented out code I delete it on the spot. I don’t read it, I don’t try to understand why it’s there, I simply expunge it from existence, and you should do the same.

Robert C. Martin