开发者

Is this a good practice of immutability?

Good morning,

Suppose I have 开发者_如何学运维a class

public class Class
{
    int something;
    int[] otherThing;
}

and I want to make objects of type Class immutable. Suppose also that I have a very frequent operation which creates a new object of type Class,

public Class SomeFunction()
{
    int[] Temp = new int[] { ... };

    return new Class(1, Temp);
}

To avoid creating new objects too often, and since Tempis no longer accessible out of the method, is it too bad to set on the constructor

this.otherThing = Temp;

instead of

otherThing = new uint[Temp.Length];

for (int i = 0; i < Temp.Length; i++)
{
    this.otherThing[i] = Temp[i];
}

?

Thank you very much.


If the constructor that does this is private its fine IMO. 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.

A public constructor directly using a provided array is a bad idea on the other hand. Since that can be used to break immutability.


It is better to assign a copy of temp to otherThing so that any changes to otherThing will not change temp. You can also use the Array.CopyTo method for this purpose.

In addition you should seriously consider using IEnumerable<int> or IList<int> instead of int[] because arrays by nature work against the idea of immutability. Read this blog post by Eric Lippert.


The difference is that in the first option you always get a new instance and in the second one all the created "Class"es will point to the same array (!). So if you change something in the array in any Class, all the other classes are changed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜