118

Because immutable collections absolutely require sharing to be usable. Otherwise, every single operation drops a whole other list into the heap somewhere. Languages that are entirely immutable, like Haskell, generate astonishing amounts of garbage without aggressive optimizations and sharing. Having collection that's only usable with <50 elements is not ...


106

Why make that code legal? Take out the set { } if it does nothing. This is how you define a read only public property: public int Foo { get { return _foo; } }


101

Immutability simplifies the amount of information you need to track mentally when reading code later. For mutable variables, and especially mutable class members, it's very hard to know what state they will be in at the specific line you're reading about, without running through the code with a debugger. Immutable data is easy to reason about - it will ...


96

never mind that you get a new reference No! Do mind that fact - it is the key in understanding the point of immutable objects. -- the value has changed No, it hasn't. You have a different object with a different value in this place in the code. But any other part of the code which had a reference to the original object still has that reference to that ...


80

A mutable collection is not a subtype of an immutable collection. Instead, mutable and immutable collections are sibling descendants of readable collections. Unfortunately, the concepts of "readable", "read-only", and "immutable" seem to get blurred together, even though they mean three different things. A readable collection base class or interface type ...


61

For example, if you need to change a single property of an object, better to just create a whole new object with the new property, and just copy over all the other properties from the old object, and let the old object be garbage collected. Without immutability, you might have to pass an object around between different scopes, and you do not know beforehand ...


57

I hate how encapsulation is always framed as preventing unauthorized access. If this were the best way to think of it, immutability would indeed eliminate most of the need for encapsulation. In fact, immutability does eliminate many cases of overzealous encapsulation, where the only purpose of the encapsulation was to keep the bumbling callers out. ...


52

The question Casting your question to real life: Is it okay for your doctor to post your private medical records publicly to Facebook, provided no one (other than you) is able to change it? Is it okay for me to let strangers in your house, provided they can't steal or damage anything? It's asking the same thing. The core assumption of your question is that ...


49

With lists in functional languages, you nearly always work with a head and tail, the first element and the remainder of the list. Prepending is much more common because, as you surmised, appending requires copying the entire list (or other lazy data structures that don't precisely resemble a linked list). In imperative languages, appending is much more ...


47

OOP and immutability are almost completely orthogonal to each other. However, imperative programming and immutability are not. OOP can be summarized by two core features: Encapsulation: I will not access the contents of objects directly, but rather communicate via a specific interface (“methods”) with this object. This interface can hide internal data from ...


44

With C#5 and before, we were faced with two options for immutable fields exposed via a getter: Create a read-only backing variable and return that via a manual getter. This option is secure (one must explicitly remove the readonly to destroy the immutability. It created lots of boiler-plate code though. Use an auto-property, with a private setter. This ...


44

No, immutable objects are quite useful in general. The first and most basic reason is that concurrency in a system doesn't require a multi-threaded application. Making say... a row in a database immutable provides a lot of benefit for change tracking, collision avoidance, syncing, and backups. And while less valuable than in concurrent scenarios, immutable ...


41

An immutable class is immutable, as in, it is not mutable. You cannot change it. If you have x::String, you can be absolutely 100% certain that x will never ever change ever (or at least, if it does, people are abusing the flexibility of your language and you have every right to tell them where to go). A mutable class is not immutable. You can change it, ...


40

First of all, your characterization of immutable data structures is imprecise. In general, most of a data structure is not copied, but shared, and only the changed portions are copied. It is called a persistent data structure. Most implementations are able to take advantage of persistent data structures most of the time. The performance is close enough ...


38

First let's consider why it is useful to have strings that are immutable. Consider the following sketch: void Safe(string s) { if (!SecurityCheck(s)) { throw new SecurityException(); } Dangerous(s); } Method Safe checks to see whether string s is "safe". Perhaps by "safe" we mean "the user is permitted to access this database table", or "the ...


36

This is an oddly phrased question that is really, really broad if answered fully. I'm going to focus on clearing up some of the specifics that you're asking about. Immutability is a design trade off. It makes some operations harder (modifying state in large objects quickly, building objects piecemeal, keeping a running state, etc.) in favor of others (...


32

Encapsulation could mean that you hide the actual storage of immutable data. E.g.: class Color { private readonly uint argb; public byte Blue => (byte)(argb & 0xFF); public Color(byte red, byte green, byte blue, byte alpha) { argb = alpha << 24 | red << 16 | green << 8 | blue; } } The interface (the constructor and ...


31

This is a valid concern. While I have not measured the memory usage of Redux applications, I think that before committing to use Redux (or any other framework for that matter) you should create stress tests that emulate the data amounts, change frequency, and computation intensity of the application you are going to build. Use these stress tests before ...


28

Note, there's a culture among object oriented programmers where people assume if you're doing OOP that most of your objects will be mutable, but that's a separate issue from whether OOP requires mutability. Also, that culture seems to be slowly changing toward more immutability, due to people's exposure to functional programming. Scala is a really good ...


27

Can we really use immutability in OOP without losing all key OOP features? Don't see why not. Been doing it for years before Java 8 got all functional anyway. Ever heard of Strings? Nice and immutable since the start. I start needing persistent (in the functional sense) data structures like lists, maps etc. Been needing those all along as well. ...


24

This is a question I am interested in and I have been doing some research on. For other viewpoints, see this blog post by Noel Walsh or this question on Stack Overflow. I have some opinions I would like to offer: I think Akka, because it works with messages, encourages a "push mindset". Often, for concurrency, I would argue this is not what you want. Pull ...


24

I'll expand my comment a bit. The List[T] data structure, from scala.collection.immutable is optimized to work the way an immutable list in a more purely functional programming language works. It has very fast prepend times, and it is assumed that you will be working on the head for almost all of your access. Immutable lists get to have very fast prepend ...


23

I think an example can clarify things here a lot (I use C#, but the actual differences to Java are of minor importance for this question). Let us think of a function which does some string formatting: string MyStringFormat(string s) { s=s.Trim(); s=s.Replace(",", "."); return s; } Now, some calling code uses this function: ...


22

You are confusing two different things: Immutable means the object's memory contents cannot be modified. When you modify an immutable object (e.g, a string), the memory contents of this object are not modified. Instead: A new block of memory is allocated. The contents of the object you (tried to) modify is copied to this new block, with the part you wanted ...


22

Your code should express your intention. If you don't want an object to be modified once created, make it impossible to modify. Immutability has several benefits: The intention of the original author is expressed better. How would you be able to know that in the following code, modifying the name would cause the application to generate an exception ...


21

Reasons I can recall : String Pool facility without making string immutable is not possible at all because in case of string pool one string object/literal e.g. "XYZ" will be referenced by many reference variables , so if any one of them changes the value others will be automatically gets affected . String has been widely used as parameter for many java ...


21

It's worth considering what the actor model is used for: the actor model is a concurrency model that avoids concurrent access to mutable state using asynchronous communications mechanisms to provide concurrency. This is valuable because using shared state from multiple threads gets really hard, especially when there are relationships among different ...


21

You're confusing immutability of reference to object and immutability of the object itself. They are separate things. laptop.memory is just a reference (pointer) to the object. This can be modified, i.e. you can change the reference to point to a different object - which is exactly what you did - you created a second String object containing "2GB" and ...


Only top voted, non community-wiki answers of a minimum length are eligible