On Tue, 16 Jul 2013 18:54:06 +0100, Jérôme M. Berger <jeber...@free.fr> wrote:

Regan Heath wrote:
Or, perhaps another way to ask a similar W is.. can the compiler
statically verify that a create-set-call style object has been
initialised, or rather that an attempt has at least been made to
initialise all the required parts.

        Here's a way to do it in Scala:
http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html

I saw the builder pattern mentioned in the original thread..

        Basically, the builder object is a generic that has a boolean
parameter for each mandatory parameter. Setting a parameter casts
the builder object to the same generic with the corresponding
boolean set to true. And the "build" method is only available when
the type system recognizes that all the booleans are true.

But I hadn't realised it could enforce things statically, this is a cool idea.

        Note however that this will not work if you try to mutate the
builder instance. IOW, this will work (assuming you only need to
specify foo and bar):

auto instance = builder().withFoo (1).withBar ("abc").build();

This looks like good D style, to me, in keeping with the UFCS chains etc.

but this won't work:

auto b = builder();
b.withFoo (1);
b.withBar ("abc");
auto instance = b.build();

But, you could create a separate variable for each with, couldn't you - v/ inefficient, but possible. I don't think this syntax/style is a requirement, and I prefer the chain style above it.

        Something similar should be doable in D (although I'm a bit afraid
of the template bloat it might create…)

Indeed. The issue I have with the builder is the requirement for more classes/templates/etc in addition to the original objects. D could likely define them in the standard library, but as you say there would be template bloat.

R

--
Using Opera's revolutionary email client: http://www.opera.com/mail/

Reply via email to