lazy construction of an immutable object
Puming via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 15 17:38:44 PDT 2014
On Tuesday, 15 July 2014 at 17:09:04 UTC, Meta wrote:
> On Tuesday, 15 July 2014 at 15:48:10 UTC, Puming wrote:
>> wow, that's interesting :-) Is it the idiomatic approach to
>> initiate immutable objects lazily? Or do people use data class
>> with immutable fields and generate a companion builder class
>> at compile time?
>
> There's no real idiomatic approach, I think, because this is
> somewhat unexplored territory. I'd say constructing the object
> inside a pure method so it can be implicitly cast to immutable
> is more typesafe, but if you're storing the immutable reference
> to the object in a class or struct, it can only be initialized
> in that class's/struct's constructor. So the following isn't
> possible:
>
> struct Test
> {
> immutable(int*) n;
>
> private int* getPtr() pure
> {
> int* n = new int;
> *n = 42;
>
> return n;
> }
>
> public void initialize() pure
> {
> n = getPtr();
> }
> }
>
> void main()
> {
> auto t = new Test();
> test.initialize();
> }
So this means that the pure method approach should also be
transitive: the containing class should also be mutable (having
the desired immutable object as a mutable field) and later freeze
itself.
If there is a complex hierarchy of objects, there are three
strategies:
1. define all classes and fields mutable, and use immutable value
in the business logic code. This would work, but lose the
compilers help with checking immutability in all conditions. For
example, you coud modify the mutable reference if it is leaked.
2. define all classes and fields immutable, and only use
constructor to eagerly create objects and there fields. This is
the most strict, but will incur some inconvenience in
asynchronous environments, where not all parts of the data is
available at start.
3. define all classes and use template magic to generate
companion builders just like protobuffer does. But that would be
complicated and I don't know how to do it. Do you have any
suggestion for this approach?
More information about the Digitalmars-d-learn
mailing list