Layout

  • Misleading indentation correlates with bug-prone software
  • Use a consitent style (eg. Tab vs Spaces)

Code Clutter

  • Remove redundant declarations and check for unreachable code
  • Programs with unnecessary code correlate with higher rate of defects
  • The intended audience for code is usually other programmers so it must be easy for them to read it

Commenting

  • Inidvidual comments are typically not the problem, the problem is usually determining what a group of operations are trying to achieve
  • Code comments should be in sync with any code changes

Variables

  • Variable names should convey what they are being used for
  • Be consistent with where you declare or initialise variables (either right at the start or just before they are used but not a mix of both styles)
  • Reduce the scope to the narrowest scope possible

Error Messages

  • Keep error messages meaningful. Avoid using numbers as error codes directly. Use labels if possible
  • Do not use NULL indiscriminately. Call out instances if a function returns NULL

Conditionals

  • Make sure an else clause is specified else implied correctly
  • Add an else clause even if empty to show you have considered the alternative
  • Code become more readable when it takes human habits into account. Conditionals and their exceptions should be formatted for clear reading of how the condition is applied (Always lead with the normal case)
  • Use guard clauses at the start to catch exceptions followed by the normal subroutine
  • Add breakpoints if the entire list of conditionals need not be evaluted
  • In case of I/O a while loop can process data incrementally and may be useful instead of using a for loop and having to read the entire data beforehand into the memory
  • A common way that an infinite loop is created using a while loop is that the increment is done within the loop
  • Humans don’t have a strong intuition for programming loops (Pane and Myres, 2001)
  • Keep the hopusekeeping code together for easiliy understanding what is happening (eg. counter in for vs while loop)
  • Loops should not exceed screen height
  • Loops should have ideally have one exit point
  • for loops are usually better for ranges and while loops for arbitrary looping

Expressions

  • Avoid long, single expressions with many parantheses

  • Humans tend to get confused with excessive negations, use De Morgans Law if needed

  • When ranges are used to classify values (eg. program to assign grade based on score) check if all values are covered and there are no comparisons that lead to multiple coutcomes instead of one

  • Ranges should not overlap. In cases of working with ranges, make sure to use upper and lower bounds to cover all cases

Bad Programming 101: Part 2