Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

11
  • 4
    To be fair multi-threading isn't the only scenario where you make objects immutable. Immutable objects allow you to verify their state during construction and then never have to do so again since they can't have their state changed to invalid later. For this reason I make objects that deal with unmanaged resources immutable usually. Also since the validity is only tested at one point, that means only one place in consuming code do you need to worry about your object complaining about invalidity. After construction, every other part of code consuming the object can know it's valid. Commented Apr 8, 2013 at 15:52
  • 2
    I guess my point is there's no such thing as "correct." Asking simply for "which way is correct" in this scenario is meaningless, because the answer is "it depends." However, feel free to enumerate all of the use cases for immutables and let the OP pick the one that fits. :) Commented Apr 8, 2013 at 15:53
  • 1
    True, I deliberately didn't answer this question because it's pretty vague Commented Apr 8, 2013 at 15:56
  • I mean, if I have a mutable array that is a member of the object, then it makes sense to return immutable copy in getter method (to provide access control and encapsulation). But if I have method like in example. I need only immutable object for using. But creating immutable copy of array is additional operations. Does it make sense to make it immutable? Commented Apr 8, 2013 at 17:16
  • 2
    Immutable objects are not only about multi-threading, like Jimmy Hoffa correctly pointed out. Making an object immutable also makes it simpler to reason about single-threaded code: for example, if I see x mentioned somewhere, more code follows, then x again, I know it represents exactly the same value or object state as before; I don't even have to look at the function calls in between. Commented Apr 8, 2013 at 20:16