Software Development: The Magical Number Seven, Plus or Minus Two

Cognitive Complexity

Abhimanyu Singh
2 min readOct 17, 2019
Cognitive Processing

Background

George Armitage Miller published a paper about limits on our capacity for processing information in 1956, often known as Miller’s law. It is often interpreted to argue that the number of objects an average human can hold in short-term memory is 7 ± 2. So, while reading code, someone might run into this limit.

Definition

Cognition is “the mental action or process of acquiring knowledge and understanding through thought, experience, and the senses.” So, cognitive complexity is the measure of code readability. Following the sited paper, the minimum and maximum cognitive complexity value should be 5 and 9, respectively.

Calculation

Consider the following three rules:

  • Using language shorthands to collapse multiple statements into one is not considered complex; therefore, it does not contribute to the complexity score.
  • Conditionals, sequences of && and || operators, loops, break, continue, goto, recursion, and catching exception contribute to the complexity score. These are called flow breaking structures.
  • Nesting of flow breaking structures contributes to the complexity score.

Note that:

  • The nesting level for else if and else branches are not counted towards the complexity score.
  • There is no increment in the cognitive complexity when using the lambdas, closures, procs, nested methods, and similar features. Such constructs do increase the nesting levels.

Language Shorthands

Using a safe navigation operator provided by the language, which returns null if the first argument is null, otherwise performs a dereferencing operation. Using such a construct avoids conditional checks. The safe navigation operator is also known as:

  • Optional chaining operator (Swift)
  • Optional subscript operator (Swift)
  • Safe call operator (Kotlin)
  • Existential operator (CoffeeScript)
  • Null-safe operator (Scala)
Example: Swift Optional Chaining Operator
Example: CoffeeScript Existential Operator

Examples

JavaScript: Cognitive Complexity Calculation Example
Java: Cognitive Complexity Calculation Example

Why Cognitive Complexity?

Any piece of code requiring keeping track of too many variables, loops, and conditional is not trivial to understand because getting a mental picture of the algorithm becomes difficult. No doubt, it is easier to debug and improve any code which is easier to read and understand.

📝 Read this story later in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--

Abhimanyu Singh

Staff Software Engineer at HackerRank. Passionate about tech, career growth, and math. Exploring number theory and sharing insights on personal development.