Consistency, Templates, Constructors, and D3
F i L
witte2008 at gmail.com
Mon Aug 27 16:09:10 PDT 2012
foobar wrote:
> FiL's scheme looks backwards to me. One of the main drawbacks
> of factories is the fact that they have non-standard names.
> Given a class Foo, How would I know to call a factory newFoo?
Well you'd know to call constructor functions because their name
implies they construct an object: new(), load(), from(T), etc.. I
_hate_ global functions like in my newFoo() example. I was simply
using it as an example of where factories hide information about
what's being returned in today's code. Constructor functions in
my proposal must always be attached to a type, and can't be
global, but their names are arbitrary (which is good for overload
distinction, like I've explained before).
> class LimitedAccount : Account {
> // "regular allocation" - on GC heap
> private Account new(Person p) {
> return GC.allocate!LimitedAccount(P);
> }
> // init
> this(Person p) {...}
> ...more code...
> }
>
> class Bank {
> Account new(Person p, AccountType t) {
> switch(t) {
> case AccountType.LIMITED: return LimitedAccount.new(p);
> ... more cases...
> }
> }
> }
>
> // usage:
> Account acc = Bank.new(PoorShmoe, AccountType.LIMITED);
This is pretty much exactly what I am advocating except I think
the allocator and c-tor can be combined (with a attribute
override), since the allocator is implicit half the time. I gave
an example in my original post:
class Foo {
this new() {
// Implicitly allocates Foo.
}
this new() @noalloc {
// Allocation must be explicit
// but must return type Foo.
}
static auto new() {
// Regular factory function.
// Allocate and return at will.
}
}
More information about the Digitalmars-d
mailing list