Reduce Complexity and Cognitive Load
How to keep clean code
cleancode
Reduce Complexity and Cognitive Load
Congnitive Load refers to the amount of mental effort required to complete a task. Cognitive load increases as code becomes more complex. “Too complex” usually means “can’t be understood quickly by code readers.” It can also mean “developers are likely to introduce bugs when they try to call or modify this code.”
Cognitive load is often higher for other people reading code you wrote than it is for yourself, since readers need to understand your intentions. One of the reasons for code reviews is to allow reviewers to check if the changes to the code cause too much cognitive load.
The key to reducing cognitive load is to make code simpler:
- Keep functions small
- Single Responsibility Principle
- Create abstractions to hide implementation details
- You should also consider the cost of abstraction
- Simplify control flow & Reduce Nesting
- Minimize mutable state
- Include only relevant details in tests
- A good test should include only details relevant to the test, while hiding noise.
-
def test_get_balance(): account = _create_account(BALANCE) self.assertEqual(account.GetBalance(), BALANCE)
- Don’t overuse mocks in tests