Named constructors
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Jan 9 17:46:52 UTC 2019
On Wed, Jan 09, 2019 at 05:30:32PM +0000, Atila Neves via Digitalmars-d wrote:
> On Wednesday, 9 January 2019 at 07:47:02 UTC, Dru wrote:
> > Another way to distinguish between constructors is needed. Because
> > it is possible to have two different constructors that take the same
> > arguments. Adding dummy arguments that are unused hurts code
> > clarity.
>
> Adding dummy arguments is unecessary. Just use the type system:
>
> struct Person {
> this(FirstName firstName, LastName lastName) { /* ... */ }
> }
>
> struct FirstName { string value; }
> struct LastName { string value; }
+1. That's what the type system is for. Dummy arguments are NEVER a
good idea unless there's a need for the API to be uniform.
It also makes the calling code self-documenting without needing language
support for named arguments:
auto myPerson = Person(FirstName("John"), LastName("Doe"));
rather than the opaque (and thus error-prone):
// Bug 1234: hmm, is it first name first, or last name first?
//auto myPerson = Person("Doe", "John");
auto myPerson = Person("John", "Doe");
T
--
Bare foot: (n.) A device for locating thumb tacks on the floor.
More information about the Digitalmars-d
mailing list