Coding standards

Coding standards are rules for writing code. They help all the humans on the project understand your work.

We have a few coding standards in this course.

  • Use meaningful variable names
  • Indent
  • Option Explicit
  • Chunky comments

Meaningful variable names

Some code:

Code

Hey, cat, what does that code do?

Scared cat

Exactly. The same code with meaningful variable names:

Tip code

What's that?

That's the tip program

Right!

Always use variables names that match the purpose of the variables in the program. For the tip program, amount is a better variable name than e29.

Use camel case

When a variable name has two words stuck together, use camel case. The first letter of the name is lowercase. All other letters are lowercase, except for the first letter in each new word.

Say you have a variable for interest rate:

interestRate Right
interestrate Wrong
InterestRate Wrong
interest_rate Wrong
h32 Very wrong

Some more examples, some a little strange:

winnieThePooh Right
sumSquared Right
snape Right
returnOnInvestment Right
roi Right
highestRoi Right

Check out the last three. ROI is an acronym for return on investment. When you use an acronym in a variable name, treat it like any other word. All lowercase if it's the first part of a variable name, uppercase first letter if it's not the first word.

Camel case is just one way to write variable names. There are other standards. As long as the variable names are easy to understand, each standard is as good as any other. Pick one standard and go with it. We'll go with camel case.

Indenting

Indent your code like this:

  1. Private Sub cmdRun_Click()
  2.     'Declare variables
  3.     Dim animal As String
  4.     Dim sound As String
  5.     'Get data from spreadsheet
  6.     animal = Cells(1, 2)
  7.     'Compute sound
  8.     If animal = "dog" Then
  9.         sound = "woof"
  10.     ElseIf animal = "cat" Then
  11.         sound = "meow"
  12.     Else
  13.         sound = "Don't know"
  14.     End If
  15.     'Output to spreadsheet
  16.     Cells(2, 2) = sound
  17. End Sub
Indent code in Subs, Ifs, and loops.

Option Explicit

This should be the first line in your program. If it isn't there, you'll waste time finding misspelled variables names. Can lead to screaming.

Screaming

See the tip about declaring variables for more.

Chunky comments

Programs are written in chunks, like Input, Processing, and Output. It’s a good idea to add a comment identifying the start of each chunk. For example:

Chunky comments