Object-Oriented Programming

Coding Style

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"
  • Often, the code is the only documentation of the design
  • 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, or 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 the "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, you can't tell by looking
  • Problem: Lack of understanding of a tab (and tab stop).
  • Confusion: Developers who use spaces to indent often have the editor expand tabs to spaces

Inconsistent Indentation

Indentation Guidelines

  • Don't mix tabs and spaces for the indentation on different lines
  • Don't mix tabs and spaces for the indentation on the same line
  • Many of the advantages of tabs have been replaced by IDE features. Advice: 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

Newlines

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

Whitespace

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

Consistent, Scalable, Maintainable

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 many more essential things in a project than minor coding style decisions