Code Reability

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Code

  • Developers read code much more than they write code
  • In the long run, there is no “your code” and “my code”
  • Common coding style/coding standard is necessary

Essential Parts of Coding Style

  • Indentation
  • Newlines
  • Whitespace
  • Comments
  • Naming conventions

Other Parts of Coding Style

  • Header and class/method/function comments
  • Libraries used, e.g., C++ standard libraries + Boost
  • Preferred language statements, e.g., switch vs nested-if statement

Characteristics of a Coding Style

  • Consistency
  • Scalability
  • Maintainability

Inconsistency

Scalability Problems

Difficult to Maintain

Problems with a Coding Standard

  • Lack of formal training
  • Programming language differences
  • Difficult to formally define/check/correct
  • Difficult to maintain
  • Lots of corner cases
  • Religious arguments
  • bike shed painting

Indentation & Whitespace

  • Indentation must be consistent
  • Indentation should appear consistent, even when moved out of the IDE, e.g., Gists, web examples etc.
  • Indentation is based on “flow of control”, not importance/difficulty

Indentation Composition

  • How much to indent for each level? 2? 4? 8?
  • What is the indentation made up of? spaces? tabs? tabs/spaces?
  • Problem: Most of the time, can’t tell by looking
  • Problem: Lack of understanding of what a tab (and tab stop) is.
  • Confusion: Developers who use spaces to indent often have the editor expand tabs to spaces

Inconsistent Indentation

Indentation Suggestions

  • Don’t mix tabs and spaces on different lines to indent, i.e., one line uses spaces, another lines used tab characters
  • Don’t mix tab and space characters on the indentation on the same line
  • Many of the advantages of tabs have been replaced by IDE features
  • Advice: Just use spaces (llvm coding standard), especially with code that may get used in multiple projects
  • If you are going to use tabs, only use them for flow-of-control indentation, and not to line things up
  • Indentation level: Linux is 8, llvm is 2(!), 4 is good

Know Your Editor/IDE Settings

Consistent, Scalable, Maintainable

Newlines

  • Single newlines are sufficient. Multiple newlines are not needed
  • Again, consistency

Whitespace

auto area = width * height;

Comments

  • Code is written in paragraphs, chunks/hunks of code
  • Comments appear before, indented the same, space after “//”
  • Prefer line comments, unless multiple lines
  • Tend towards doxygen comment markup
    • Note: There are many styles of Doxygen markup

Summary

  • Consistency, Consistency, Consistency
  • Coding styles often reflect a compromise
  • With existing code, adapt to the coding style of the existing code/project
  • Be open to updating your coding style over time
  • There are much more important things in a project than minor coding style decisions