Fri, 1 May 1998 12:28:41 -0500
>John, as we struggle with how to best do constructors, could
>you publish some example code that does it elegantly? I would like to
>learn less-restrictive methods of doing Ada-95.
Well, I'm not John, but I suggest that you download and look at the design
of Claw (you can download a demo version from www.rrsoftware.com).
Claw was designed from the ground up using the OOP features of Ada 95. We
considered the constructor issue. Our solution is to use Create functions
where that makes sense (see Claw.Pens, for instance).
We considered solutions using discriminants, but rejected them because they
always ended up requiring the types to be limited and objects to be
declared at the library level. (That's because some access discriminants
always seems to be needed). We thought that assignment and local objects
were much more important than fancy constructors.
The only thing lost by this formulation is a requirement to call a
constructor. We didn't find this important; let me explain why.
In Claw, objects are always either Valid or Invalid. (The Initialize
routine is used to guarantee that objects start Invalid). All Claw
routines check their arguments for validity, and raise Not_Valid_Error is
given an invalid argument.
Therefore, failure to Create an object shows up immediately as a
Not_Valid_Error from the first operation which uses it. Assuming your
compiler provides useful Exception_Information, finding and fixing the
error is trivial, and does not require the use of a debugger. Even the
simplest coverage-based testing plan would have to uncover the error, so
the odds of it going undetected are small.
Claw objects would need an Invalid state (and therefore the checks) even if
it had required constructors. That's because they must have an explicit
Destroy routine. (You wouldn't want to force windows to stay on the screen
until the underlying object is finalized.) Since objects can be Invalid
anyway, forcing an initial state doesn't buy much.
My opinion is that any object for which explicit destructors can be called
(and this describes most object classes) must have some similar mechanism.
Therefore, Ada 95's lack of a fancy constructor mechanism is at worst a