Syntactic Sugar for Virtual Constructors?

BCS BCS at pathlink.com
Thu Feb 28 09:40:10 PST 2008


Janice Caron wrote:
> On 28/02/2008, BCS <BCS at pathlink.com> wrote:
> 
>>        AbstractBaseClass this(string s, int i)
>>        {
>>                switch(s)
>>                {
>>                        case "Foo": return new DerivedClass(i);
>>                        ...
>>                        default: return null;
>>                }
>>        }
> 

your point is valid (in some cases) but totally orthogonal to mine. Re 
wright it as this:

AbstractBaseClass this(string s, int i)
{
	// code to return a sub type of
	// AbstractBaseClass based on value of s
	// or null on an argument error so that
	// check code causes exception
}

and no important feature of my suggestion is changed but your point 
vanishes.

> 
> The switch is the one thing that you /must not have/. The factory
> cannot possibly know all possible (present and future) derived
> classes.

But it might /in some cases/ known all the /valid/ ones

> Putting that switch statement there prevents anyone without
> access to the source code from making new derived classes,

Re-read that last, but in a "good thing" context. in some cases it will 
be a good thing.

> making the
> mechanism completely unworkable for a library.

over generalized: unworkable for /some/ (or even many) libraries

> Also, this mechanism
> needs to import all of the module(s) where the derived class(es)
> is/are defined, which is also bad.

In line with the above point of view; this is unavoidable for some cases.

> Also, the function above would
> cause "executable bloat", whereby every possible derived class will
> end up in every executable which calls that function, whether needed
> or not.

Every possible derived class that can get used at run time will have to 
be available some how for any solution. The only escape would be lazy 
loading of DLL's or SO's and that can be used in my solution as well.

> 
> The good way to implement a factory function is to call the function
> object.Factory(). That way, the factory function needs 


> [the function will have] /no knowledge/
> of the derived class, beyond it's class name,

read that in a "bad thing" context. Again, it can be.

BTW, I was not proposing that my solution is a better way to do what you 
are looking to do, I'm proposing it as a clean solution that can do 
something more general than what you are looking for.



More information about the Digitalmars-d mailing list