The difference between a professional programmer and somebody who is just learning, tends to be that the professional programs are a little neater, cleaner, and maintanable. Basically, the professional has a better style, after years of experience.
In addition, one would hope that the professional program will be a little more efficient and less buggy. But that doesn't always happen.
The intent of this page is to give you some tips for programming style.
This benefits you when you come back later and try to fix, expand, or reuse an old program.
It also benefits others when you share your work with them. It's great to share your programs with others, but you're not doing them a favor if you give them something that they can't figure out!
For most of our examples, we will use hypothetical code intended to center content in a display
that is 18 inches wide.
Here is a version that is a little more readable:
X = (18 - W) / 2
CenteredPosition = (DISPLAY_WIDTH - ContentWidth) / 2
Sometimes you want a big "block comment" that describes the overall
task to be accomplished by the next few lines:
You can also put a comment on the end of a line,
explaining what it does:
In either case, whenever you come back and change the program later,
you must update the comments.
If you change the code without changing the comments,
the commentary can devolve into lies that mislead you in the future.
You often ended up with lines like
Things are a lot better now, with most programming languages allowing longer names for variables.
Unfortunately, old habits die hard and some programmers still use short names.
Yes, I suppose it saves a little on typing, but it makes the code hard to read.
I suggest that you use longer names and take advantage of that length to make them more meaningful.
Isn't
It also helps if you name these symbolic values in such a way that they are clearly distinct from variables.
E.g.,
There are two reasons why this is often a good idea:
Our hypothetical code
You might come back to this program later and spend a bit of time wondering where the "18" came from.
Since our improved code uses "DISPLAY_WIDTH" everywhere, it is easy to change the program to run on
a display that has a different width.
Just go to where "DISPLAY_WIDTH" is set up and change it in that one place.
Any decent compiler will keep a pool of literals and reuse them,
so you don't save space by refering to a single value.
The compiler will use inline values for small numbers, so speed is not an issue.
(Heck! It might even optimize that division by two into a shift right operation!)
As a result of this, professionals sometimes over-design a program.
This takes many forms:
"Yes, I only need to control a single talking skeleton now.
But someday I may want to control an entire musical band of skeletons,
so I'll write the program to run five skeletons and only use the first part now."
The biggest problem resulting from this is that the program becomes more complex and harder to
write and debug - all without knowing for sure whether or not this additional work will pay off.
After all, you may never get around to that musical band of skeletons.
Or when you do, you may discover that you are using a different controller
and the program must be rewritten.
"Sure, a linear search is easy to code, but it would run faster if I used a height-balanced tree structure."
Once again, we are adding complexity to reach a goal that might or might not be necessary.
But these situations are usually rare.
Most of the time, it is better to just get the darn program working,
and then to tune it up later - if you need to.
Because often the simple approach works just fine and you don't need to further optimize it.
Side note to professionals reading this:
But not all programs really need to be efficient.
For those that do, you should know in advance.
If you are monitoring a nuclear explosion in realtime, you will have stringent performance
metrics laid out in advance.
If you are operating a talking skeleton, the code doesn't have to be that fast.
Lastly, when you suspect that performance will require optimization,
you can plan for the optimization and not implement it until it is needed.
"Eventually, we'll need to speed up data retrieval by putting a cache here.
Let's get it running first, then add the cache when the program does so much work that it starts to slow down."
Here are some examples of how things could get silly of you go overboard:
There isn't really anything wrong with that line.
In fact, "length divided in half" reads pretty well.
But is it necessary to go that far?
Use Comments
Every programming language has a way that you can put words into the program that aren't
translated into something that is actually run by the computer.
This allows you to write notes and comments for future reference.
' Wait for the Trick-or-Treater.
'
' To be sure that the kid is really there, make sure that we see
' the KidPresent several times in a row (ideally a full second)
' before actually starting.
SStartAgain:
KidWait = 0
SLookAgain:
IF KidPresent = No THEN SStartAgain ' if no kid, start at the beginning
KidWait = KidWait + 1
IF KidWait < 20 THEN SLookAgain ' keep looking until we see kid many times
PULSOUT MonsterRoar, 1 ' 10 µs pulse to sound chip; make monster roar
Use Meaningful Variable Names
In the ancient days of computer programming, variable names were limited in length,
sometimes to a single letter.
X = (18 - W) / 2,
and if you left the program and came back to it a month later, you could spend hours
trying to figure what you had originally intended.
CenteredPosition a bit more indicative of the result that we are getting from the calculation?
Isn't ContentWidth helping you to figure out what is going in to the math?
Avoid Magic Constants In The Code
This little bit of advice suggests that you avoid scattering constants throughout your program
and instead create symbolic names with the values.
DISPLAY_WIDTH is a symbolic value that shouldn't change,
while ContentWidth is a variable that will probably have a different value for every line.
X = (18 - W) / 2 has that 18 sitting in there.
What does it mean?
Why not 19 instead of 18?
X = (DISPLAY_WIDTH - W) / 2
Is more meaningful when you read it.
Don't Over-Design
The professional programmer has a serious handicap:
Geeks love things that are high-tech, flexible, and powerful.
Programmers who follow "agile" development methods usually adhere to the rule,
"Do the simplest thing that could possibly work."
Optimize Last, If At All
There are certainly times when you have to squeeze the last bit of power out of a
computer that lacks resources.
Perhaps you have to optimize for less space (to fit the program in small memory).
Or perhaps you have to optimize for speed (so that the program can run the show without delays and gaps.
You might be thinking, "If you completely disregard efficiency,
you may paint yourself into a corner by writing a program that can't be optimized later."
Yes, that is possible.
Don't Overdo This Advice
The advice on this page is intended as general advice that will be tempered in time as you gain experience.
It is certainly possible to overdo it.
Everything in this comment is true, but it goes too far because:
' Calculate the position of the content so that it goes
' in the center of the display. The full width of the
' display is DISPLAY_WIDTH, a symbolic value which is
' currently set to 18 inches, while the ContentWidth is
' the width of the content. Subtracting the two widths
' gives the excess width of the line. To center the
' content we want to put half of this width on each side.
CenteredPosition = (DISPLAY_WIDTH - ContentWidth) / 2 ' calculate the center position