cast(immutable) vs extra variable

Daniel Davidson nospam at spam.com
Thu Sep 19 15:07:45 PDT 2013


On Thursday, 19 September 2013 at 20:05:34 UTC, Jonathan M Davis 
wrote:
> As soon as you have a const or immutable member in a struct, 
> you can't ever
> assign anything to it, even if all of its other members are 
> mutable (you could
> assign the individual, mutable members but not the whole 
> struct). That means
> stuff like if the struct is ever default-initialized, you can't 
> even give it
> another value, which tends to mean that you can't use such a 
> struct in places
> like arrays.
>

Ok. I think you can use in immutable(T)[], just not T[].

> All in all, I think that it's pretty much always a bad idea to 
> have a struct
> with const or immutable members. It's just begging for 
> problems. Tail-const or
> tail-immutable is fine, because the members themselves aren't 
> const or
> immutable (just what they refer to), but having them be 
> directly const or
> immutable is a bad idea IMHO.
>

I would like to understand the tail-const/immutable argument
better. Per this advice, it is ok to keep my members
tail-const/immutable. But it is ok if those structs to have 
members that
are const/immutable. So, why is it ok for members of classes that 
I
hold but not for my members. In the face of const/immutable
*transitivity* how is it more beneficial?

Here is a setup: Data is coming in - say over the wire or from a
database. It is very rich data with nestings of primitives, lists 
and
string keyed associative arrays, recursively - think nested json. 
Once
a data object is read in it is passed off to classes that use the 
data
in read-only fashion.

So, for example, assume the root of the rich data is a Portfolio
instance. All members of Portfolio recursively are public since 
it is
really plain old data from one perspective and this makes using 
vibe
json serialization simple. Assume that a user of Portfolio data 
is an
Analyzer. This analyzer will need to do lots of complex operations
with the portfolio that it uses in readonly fashion. It may have 
many
mutable members for intermediate calculations.

Here is a mockup http://pastebin.com/nBLFDgv6 which is making use 
of
immutable(Portfolio) to ensure that (a) the analyzer does not 
modify
the data and (b) no other code can modify the data. To achieve 
this
there needs to be a point in time where the modifiable Portfolio 
is
done being read and made immutable. At this point it is cast to
immutable and henceforth only accessed that way.

Given this setup - what do you see as the trade-offs?

What can not be done or will be challenging in face of refactor?

What are some better alternatives/recommendations?

I am a fan of D but my struggles with const/immutable transitivity
feel endless and are wearing on me. I feel like having an ability 
to
say something will not change and not using that ability is like 
being
teased.




More information about the Digitalmars-d-learn mailing list