Named constructors
Olivier FAURE
couteaubleu at gmail.com
Tue Jan 15 12:42:32 UTC 2019
On Monday, 14 January 2019 at 16:04:26 UTC, Atila Neves wrote:
> On Monday, 14 January 2019 at 14:31:09 UTC, aliak wrote:
>> auto a = Builder()
>> .accountNumber(202)
>> .firstName("Bob")
>> .lastName("Who")
>> .branch("N-2")
>> .interest(20.0)
>> .balance(10.0)
>> .build()
>>
>> ??
>
> auto a = Customer(AccountNumber(202),
> FirstName("Bob"),
> LastName("Who"),
> Branch("N-2"),
> Interest(20.0),
> Balance(10.0));
>
> struct Customer {
> this(A...)(auto ref A args)
> if(constraintVerifyingNumberAndTypesOfArgs!A) {
> this.accountNumber = args[staticIndexOf!(AccountNumber,
> A)];
> // etc.
> }
> }
I think these design patterns are useful if you really want named
arguments in your code right now, but they really shouldn't
replace the structure initialization DIP.
Personally speaking, I hate having hacks like these in my code
and would immensely prefer an idiomatic syntax eg:
auto a = Customer{ accountNumber: 202, fistName: "Bob" };
which would produce easy-to-read error messages like:
Error: `fistName` is not a member of `Customer`. Did you mean
`firstName`?
Error: Initialization list for `Customer` does not provide
value for member variable `lastName`, which has no default value
defined.
I'm having trouble guessing what error messages your Customer
structure would provide, but I imagine they wouldn't be nearly as
informative. Same thing for generated documentation.
More information about the Digitalmars-d
mailing list