Wednesday, March 23, 2011

cognitive load reduction

Debates about how to write better code (i.e. fewer bugs) revolve around increasing maintainability, but not too long ago I recognized a related and perhaps fundamental criterion: cognitive load reduction. The fewer disparate items that a developer must contemplate simultaneously, 1) the lower the chance that a mistake will slip in unnoticed, 2) the greater the amount of attention left for the details of the problem/domain rather than the twists and turns of the code. When code is confusing and demanding to comprehend, the cognitive load is greater, and therefore it's more difficult to write, trace, debug, and modify.

Awareness of impact on cognitive load should change the choices that someone makes. Sure, the first task is to produce code that meets the known requirements. Yet developers shouldn't then neglect the second task of refining the code until it's sensible. Code has two audiences, machine and human. This is a lens for perceiving the usual code debates.
  • Units of code organization with hard boundaries reduce cognitive load by freeing the reader from looking through many peripheral lines to trace execution.
  • Good names reduce cognitive load by freeing the reader from inferring what a variable is for.
  • An easier build process reduces cognitive load by freeing the builder from rehearsing and reciting a series of error-prone manual steps.
  • Version control that meets the team's needs reduces cognitive load by freeing the team from devising complicated workarounds.
  • Domain models that match the way that everyone thinks (according to common agreement) reduce cognitive load by freeing them from continual lossy translation of one another's statements.
  • Frameworks reduce cognitive load by freeing the reader from examining custom-made immature solutions to ordinary incidental problems, e.g. templating, MVC, protocols. On the other hand, obtrusive frameworks may increase cognitive load by overshadowing and complexifying the base code without marginal benefit.
Effective writing in natural human language doesn't place an excessive burden on the reader, who's trying to interpret the message. Similarly, effective writing in programming language doesn't place an excessive burden on the maintainer, who's trying to interpret the code's intent.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.