What's the preferred way to mandate that objects be created by
the use of given "constructor" subprograms?
By this, I mean that I want to create a type and the only way to
get new values of this type is to use a subprogram that I provide.
* It's a record type.
* A few of the components must be set to "sensible" values before
use.
* What constitutes a "sensible" value isn't known until runtime.
* I don't particularly want to add "is initialized" checks on all
subprograms in the package.
Regards,
xw
Declare your type to have unknown discriminants:
package P is
type T (<>) -- unknown discriminants: objects requires
initialization
is [limited] private;
function Construct return T;
private
type T is [limited] record ... end record;
end P;
If the type is limited, the only way for a client to create an object
is to call Construct. If the type is nonlimited, the client has two
ways: call Construct or copy an existing object to a new one.
Inside Construct, you would normally use the extended return statement
(ARM 6.5(2.1/2)), e.g.
function Construct return T is
begin
return Object : T do
-- initialize some components
end return;
end Construct;
You can also make your type controlled or limited controlled. You can
expose the controlledness in the public part or hide it in the private
part.
--
Ludovic Brenta;
Nice, thanks. I knew it was something along these lines...
>
> You can also make your type controlled or limited controlled. You can
> expose the controlledness in the public part or hide it in the private
> part.
This raises a good point, actually - I've never really been sure what
the advantage is of exposing the controlledness (or hiding it, for
that
matter). I hide everything by habit but I'm not sure if I'm causing
a consumer deep problems down the line...
Regards,
xw
> Declare your type to have unknown discriminants:
[...]
I find the following to be a nice summary of possible strategies:
http://en.wikibooks.org/wiki/Ada_Programming/Types/limited#Initialising_Limited_Types
--
Maciej Sobczak * www.msobczak.com * www.inspirel.com
Database Access Library for Ada: www.inspirel.com/soci-ada
> Inside Construct, you would normally use the extended return statement
> (ARM 6.5(2.1/2)), e.g.
Or an aggregate, "return (This => ..., That => ...);"
or a function call, "return Something(This => ..., That => ...);".
> function Construct return T is
> begin
> return Object : T do
> -- initialize some components
Or:
return Object : T := Something(This => ..., That => ...) do
... -- overwrite some components
All of the above possibilities work in the limited case.
- Bob