liveBook · Manning

Cognitive complexity

As explained in Troubleshooting Java, Second Edition

The mental difficulty of understanding code investigation as the number of nested reasoning paths and open investigative plans increases.

Cognitive complexity is the mental difficulty of investigating code as each deeper instruction opens another reasoning path and investigative plan. section 2.1

Code investigation moves both through a method and into the methods it calls. Each jump leaves a plan behind, making the behavior harder to assemble mentally. section 2.1

Manage investigation complexity by asking focused questions:

  • Check whether a constructor only creates an object or also changes input-related state. section 2.1
  • Check whether a method returns a value, changes object state, or does both. section 2.1
  • Choose whether to skip an instruction for a simpler investigation or inspect it for greater certainty. section 2.1

Tracing a decoder

A Decoder loops through input strings, extracts digits, sums them, and returns the total. Understanding the extractor requires opening another investigation plan. section 2.1

Listing 2.1 An example of a method to debug
public class Decoder {

  public Integer decode(List<String> input) {
    int total = 0;
    for (String s : input) {
      var digits = new StringDigitExtractor(s).extractDigits();
      total += digits.stream().collect(Collectors.summingInt(i -> i));
    }

    return total;
  }
}

Inspect the Java method whose constructor and extractDigits call create the hidden behavior that must be investigated. section 2.1

How Troubleshooting Java, Second Edition covers it

How deep it goes
Explains nested reasoning plans and investigation trade-offs, but stops short of formal measurement or debugging metrics.
Examples
Uses a Java Decoder method, StringDigitExtractor calls, and questions about returned digits and changed state.
What you can do after
Diagnose/debug with it by controlling investigation depth and tracing hidden behavior behind method calls.
How it connects
Connects code analysis with debugging, methods, constructors, object state, and large language models.

Also explained in

Compare how 2 books explain cognitive complexity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Troubleshooting Java, Second Edition. The section links point to the parts of the book it draws on.