Cognitive Complexity and its effect on the code

Humans can easily keep in mind about 7 entities +/- 2(wikipedia).
When somebody needs to read the code they may run into this limit. Sometimes there are too many local variables to keep track of, or too many if/for statements. In all cases it makes it harder to understand what the code is supposed to do because it’s hard to keep a mental picture of the algorithm.

Industry standard: No.

Readability and maintainability: It’s easier to debug/improve code that is simple and easy to read.

Applies on methods or other parts: Everything that some human might want to understand. If you try to explain your design and I need to keep track of 20+ classes, I’ll be lost. If I need to work quickly with your interface but I need to remember 10 bits of state, I won’t be able to.

Any specific criteria it depends on: The amount of things one needs to remember to understand the code.

Best practices: Make more and better defined functions. Extract related concepts into groups/packages. Reduce the number of nesting levels in the code (if you read a nested code you need to remember the condition that got you there). Reduce the number of in use variables at any one point (works great with extracting functions).

Leave a Comment