Game Development Reference
In-Depth Information
Any operation with some meat to it should be called explicitly. This might annoy your
sense of cleanliness if you are the kind of programmer who likes to use C++ con-
structs at each and every opportunity. Of course, there are exceptions. One is when
every operation on a particular class is comparatively expensive, such as a 4 × 4
matrix class. Overloaded operators are perfectly fine for classes like this because the
clarity of the resulting code is especially important and useful.
One thing to watch out for is that the C++ compiler will magically generate functions
in your class. It will silently generate a copy constructor, copy assignment operator,
and destructor for you if you don ' t create them yourself. If you don ' t create any con-
structors, it will also generate a default constructor. These will all be public functions.
This can cause unintended side effects if you
s happening under
the covers. To get around this, you can make copy constructors and assignment
operators private, which keeps programmers from assuming the object can be dupli-
cated in the system. A good example of this is an object in your resource cache, such
as an ambient sound track that could be tens of megabytes. You clearly want to dis-
able making blind copies of this thing, because an unwary programmer might believe
all he
'
re not aware of what
'
s doing is copying a tiny sound buffer.
A recurring theme throughout this topic is that you should always try to avoid sur-
prises. Most programmers don
'
'
t like surprises because most surprises are bad ones.
Don ' t add to the problem by tucking some crazy piece of code away in a destructor
or similar mechanism. It
'
s important to remember that you
'
re not writing code for
the compiler, you
re writing code for other programmers. The compiler will be just
as happy with clean code as it will with sloppy code. The same is not true for another
programmer.
'
Class Hierarchies: Keep Them Flat
One of the most common mistakes game programmers make is that they either over-
design or underdesign their classes and class hierarchies. Getting your class structure
well designed for your particular needs takes real practice.
A good rule of thumb is that each class should have a single responsibility in your
code base and should have inheritance trees that are no more than two or three levels
deep. As with anything, there are always exceptions to this rule, but you should strive
to flatten your hierarchy as much as possible.
On the opposite end of the spectrum, a common problem found in C++ programs is
the Blob class, as described in the excellent book Antipatterns by Brown et al. This is
a class that has a little bit of everything in it and comes from the reluctance on the
programmer
'
s part to make new, tightly focused classes. In the source code that
 
 
Search WWH ::




Custom Search