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:
Hey, cat, what does that code do?
Exactly. The same code with meaningful variable names:
What's that?
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:
Indent code in Sub
s, If
s, 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.
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: