lennxa

What Makes Code Hard To Read: Visual Patterns of Complexity

# | #code, #readability

seeinglogic on readability of code:

Let me be upfront: there is no commonly-used and accepted metric for code readability.

Proceeds to go through a couple of efforts to measure complexity - always good to have.

  1. Halstead Complexity Metrics

  2. “Cognitive Complexity”

And concludes of 8 points:

8 Patterns for Improving Code Readability

Combining the points discussed so far and merging/removing duplicates where possible, we end up with a list of 8 factors:

  1. Line/Operator/Operand count: Make smaller functions with fewer variables and operators, they are easier to read
  2. Novelty: Avoid novelty in function shapes, operators, or syntactic sugars; prefer reusing common patterns in a codebase
  3. Grouping: Split series of long function chains, iterators, or comprehensions into logical groupings via helper functions or intermediate variables
  4. Conditional simplicity: Keep conditional tests as short as possible and prefer sequences of the same logical operator over mixing operators within a conditional
  5. Gotos: Never use gotos unless you are following this one pattern, and even then only when the alternatives are worse
  6. Nesting: Minimize nested logic (aka avoid large variations in indentation). If deep nesting is required, isolate it in a function instead of deeply nesting inside a larger function
  7. Variable distinction: Always use descriptive and visually distinct variable names; avoid variable shadowing
  8. Variable liveness: Prefer shorter liveness durations for variables, especially with regard to function boundaries

Each of these applies across languages and code format/styles, and can give objective measures to use in discussions about readability.

Mostly makes sence. But, what about when you want to contain complexity? I think there are times when larger functions are okay, when the flow is linear and it's logical to contain the complexity in the function. If a function is only going to be used once, and the only effect of refactoring into seperate function is the name of the function and the indirection - you might as well add a comment and keep it there itself.

An excellent article on code complexity - Cognitive load is what matters. There's a section on small methods as well.

#code #links #readability