Reduce cognitive complexity

Kitten

Cognitive complexity is the load on your brain. The higher the load, the more likely you are to make programming mistakes.

Breaking code into smaller pieces reduces cognitive load. The break down complex conditions pattern is a good example of that. Check it out.

Functions help, by breaking code into pieces, and giving the pieces names. For example:

  • $price = getParamFromGet('price');
  • $priceErrorMessage = checkPrice($price);

When you're writing this code, you don't need to remember all the deets of checkPrice(), just what it does. You get that from the docs on the function's signature:

  • /**
  •  * Check a price.
  •  * @param mixed $price The price to check.
  •  * @return string Error message, MT if none.
  •  */
  • function checkPrice($price) {

Giving variables meaningful names helps, too. Suppose you're writing a program dealing with interest rates. You store the current interest rate in a variable called $d122. Huh? When you're writing the code, you have to remember that $d122 is the current interest rate. That means you have less short-term memory for thinking about the code.

If you call the variable $currentInterestRate, you don't need to remember what the variable is. It's clear from the name. That reduces the load on your short-term memory.

Indenting reduces cognitive complexity as well. Indenting gives you visual cues about code structure. Visual processing is powerful in humans. Indenting harnesses that power.

Bottom line: easy-to-think-about is good.