Clean Code - Google

When you read code and find it hard to understand, you're experiencing cognitive load.

Cognitive Load = amount of mental effort to complete a task.

While reading code, you have to keep in mind information such as conditional logic, data structure state, loop indices, variable values, etc. And since people can typically hold only 5-7 pieces of information in their short-term memory, code that is more complex (involves more information) increases cognitive load.

Cognitive load is also higher for other people reading the code you wrote. This is why code reviews are needed, to check if the code causes too much cognitive load.

So, be kind to your coworkers and write clean code.

The key to reducing cognitive load is to make code simpler.

Here are some principles:

  1. Limit amount of code in a function or file: Keep functions small and limit each class to single responsibility.
  2. Create abstractions to hide implementation details: functions and interfaces are abstraction to hide complex details, but don't go overboard.
  3. Simplify control flow: too many if statements or loops makes the control flow hard to understand, hide complex logic with helper functions. Reduce nesting with early returns.
  4. Minimize mutable state: stateless code is easier to understand, avoid mutable class fields, make types immutable
  5. Include only relevant details in a test: test can be hard to follow if it includes boilerplate test data that is irrelevant
  6. Don't overuse mocks in tests: improper use of mocks -> cluttered test with calls that expose implementation details

Here's a printer friendly version.

11/9/2023