Answer the question
In order to leave comments, you need to log in
Is it always necessary to strive for the immutability of objects?
I did a laboratory on OOP in c #, first I did it without immutability: for the fields that need to be changed, I left the setter, for the rest - only the getter. But the teacher asked to make objects immutable and do it with the help of a builder. I did, but the code became less clear, and it became more difficult to write tests, because when you tried to change the object, a new one was created and you had to look for this new object in order to continue working with it. Well, the question itself: in what cases is it better to make objects immutable, and in which cases it is possible to get by with the restriction of some fields?
Answer the question
In order to leave comments, you need to log in
Immutable objects have their advantages. First, they are easier to compare: instead of comparing all fields (recursively), we compare only two root references to objects. Secondly, some internal data structures can be shared. For example, a string in many PLs (C#, Java, JS) is an immutable object. And there is an optimization in JS - when we take a substring from a string, we use the same data buffer. In case of a changeable line such focus would not give a ride.
Of course, the pros are offset by the cons. It takes a long time to make changes in a large object. More load on memory and garbage collector. It is also impossible to transfer such an object somewhere and then change it - where it was transferred, there will be an outdated version (this is sometimes good, sometimes bad).
In general, compromises, a sense of proportion. Therefore, you need to look at the task, and choose which option will be more efficient and easier - changeable, unchangeable, or something in between.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question