开发者

Still Another Question About Immutable Objects

Good morning, afternoon or night,

Supposing I have a class

public class SomeClass
{
    uint   SomeField1;
    uint[] SomeField2;

    (...)
}

and a series of immutable objects A1, A2, ... of type SomeClass differing, for example, only by SomeField1, is it a good practice to set SomeField2 in all of them pointing to the same place in memory, or should I use array duplication in the 开发者_Go百科constructors even if I know the objects are immutable?

Thank you very much.


"The man" Eric Lippert has a great blog post on this which covers shallow vs deep immutability and observational immutability, this seems to be at the core of your question. If you used a reference to an array in your constructor and didn't create your own copy of the array you would only have "shallow" immutability.

The ints field is “shallowly” immutable. You can rely upon it being immutable to a certain extent, but once you reach a point where there is a reference to a mutable object, all bets are off.

Obviously the opposite of shallow immutability is “deep” immutability; in a deeply immutable object it is immutable all the way down.

In your case SomeField2 would also have observational immutability: From the point of view of any caller the field would be immutable (provided you don't grant direct access to it as @Slaks pointed out) - unless someone else changes the array you reference. If you are guaranteed that that array never changes that's all you need - this would be one application of the flyweight pattern.


One of the main reasons to use immutable data structures is that they can safely share data. If your array is never exposed and it can never change, then by all means, you should be sharing it amongst other immutable objects that need the same array.


In your old question Is this a good practice of immutability? I already stated:

Since you know the content of the other array will never change you can directly use it. You could even share one instance of the array between several instances of your class if you want to without causing any problems

So as long as you can guarantee immutability sharing instances is no problem.


If you can guarantee that no consumer of your object ever mutates the array then you can safely re-use the array as you describe. However, that seems like playing with fire to me. In this case I would be strongly inclined to actually make the field a ReadOnlyCollection<uint> that wraps the array; that way you get (1) nice clear "in code" documentation that this collection is read-only, and (2) an exception if someone attempts to violate the read-only-ness.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜