C++ Style
Here are some C++/Object Oriented programming hints. Some of these
are very specific, while others are somewhat vague. I don't apologize
for this. I don't think there's an algorithm for writing good C++.
It's more of a black art. None of the following rules are cast in
stone. In fact, a good C++ programmer knows how to delicately sacrifice
ideals to time and efficiency constraints.
-
Don't EVER duplicate code. There are languanges in which cut
and paste are some of the most important features in your editor.
C++ is not one of them. This is what object oriented programming
is all about. Even if it's just a couple of lines, put it in a function.
-
Don't EVER declare functions/constants twice. If you do, you
are writing unmaintainable code. Put them in a header file and include
it. This is of course related to the previous point.
-
Make sure your objects are always in a consistent state. In
particular, don't make a trivial constructor and then another function
called "initialize" or something, which must be called outside of the methods
of the class. This will be tempting when it seems that enough information
to initialize the object is not available at the time that it is created.
(This situation often indicates a design flaw). Always assume that
your class will be used by morons (even when it's just going to be you).
-
Group the statements in a basic block by functionality. Say you
have a block in a function in which you accomplish several unrelated tasks.
Don't interleave these computations, as this unnecessarily makes your code
difficult to follow.
-
Don't pass superfluous information. Don't pass more data to
functions than is required. For example, if all you need is a pointer
to an object, don't pass the index of this pointer in an array - pass the
pointer. If you only need one piece of data from an object,
don't pass the whole object.
-
Think hard while designing your implementation. C++ is a very
difficult language to master. It has many subtle features and traps.
The best way to do something may not be obvious. Should you pass
a copy, a pointer, or a reference? Should you make the function private/protected/public?
Should the function be static/virtual? Should your class have
a protected constructor? Should it be subclassed from something,
or should it contain an object of that type? Should it be a friend
or member function?
-
Don't go half way. C and C++ have different programming methodologies.
It is difficult to mix them effectively. Don't write C with a couple
of classes. You will probably regret it.
-
Keep your classes and header files as independent as possible.
Unnecessary dependencies are bad. Don't be lazy. Put
in the extra effort and be proud of your clean design.