PROBLEM: The constructor-destructor pair for an object can be used
to improve code quality, particularly maintenance.
RESPONSE: Allan Clarke
Designers should consider that useful work can be performed by classes
in their constructor-destructors. Functions or methods which perform
a task upon entry and undo that on exit can benefit from this technique.
By throwing the burden of calling the "undo" code onto the
compiler, the code becomes more robust and more maintainable.
For example a maintenance change might involve inserting a
conditional return into the function.
// ................................................................
An example, using Guide code is shown below. In this simple class,
the constructor changes the cursor to a new style, but remembers
the current cursor. Upon destruction, the old cursor is restored.
(Note that this is not a "heavy-weight" TObject descendent, but is
so simple as to be completely inlined, hence the naming scheme in
which the class name begins with "S".)
class SCursorPush {
private:
int fSaved;
public:
SCursorPush (int newCursor) {
fSaved = gScreen->cursorStyle();
SETCURSORSTYLE (newCursor);
}
~SCursorPush () { SETCURSORSTYLE (fSaved); }
};
void myOldFunction ()
{
int savedCursor = gScreen->cursorStyle();
SETCURSORSTYLE (g_resizeCurs);
.... do some work
SETCURSORSTYLE (savedCursor);
}
void myNewFunction ()
{
SCursorPush (g_resizeCurs);
.... do some work
}
// ................................................................