Consistency, Templates, Constructors, and D3

foobar foo at bar.com
Tue Aug 28 04:32:56 PDT 2012


On Monday, 27 August 2012 at 23:09:13 UTC, F i L wrote:
> 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.
>         }
>     }

Not at all.
Your scheme requires new to return typeof(this) whereas in mine 
Bank.new() returns an Account instance.
Also, allocation needs to be explicit in order to be useful.
Most importantly, the naming scheme you suggest breaks generic 
code. I _DON'T_ want to choose between "new/from/load/etc.." when 
I create an object. I just want to create an object, period. 
There are whole frameworks of DI just to "fix" this problem of 
new and factories.

Please google for "java new considered harmful" to read more 
about this.


More information about the Digitalmars-d mailing list