Is this a good practice of immutability?

时光怂恿深爱的人放手 提交于 2020-01-17 01:22:07

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5218600/is-this-a-good-practice-of-immutability

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!