开发者

java: advantages of immutable objects in examples [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago. 开发者_JAVA百科

give me please examples where I could see advantages of immutable objects. Info I found in internet are concentrated in threads. I don't know about threads yet. would be great if the examples would use simple principles


Immutability is important in multi-threaded programs, because then you know that one thread won't corrupt a value used in another thread. But it's also useful in a single-threaded program.

Here's a simple example:

Integer i=Integer.valueOf(17);
foo(i);
bar(i);

You might well want to know, What value is passed to bar()?

Suppose that foo() is a big, complex function. In this example, I know for an absolute fact that when foo completes, i is still equal to 17, because an Integer is immutable. Were that not true, I would have to study foo to tell if it might be changed or not.

Here's a slightly more complex example. Suppose I have some object that resembles an Integer, but is mutable. Let's call it MutableInteger. Then say I write this:

MutableInteger currentInventory=findQtyInInventory();
MutableInteger neededInventory=currentInventory; // copy current for starters
... bunch of other code ...
neededInventory.subtract(allocatedToSales);
currentInventory.add(arriving);
... bunch of more code ...
if (neededInvenory.compareTo(currentInventory)>0)
  display("Shortage!");

Do you see the problem with the above? neededInventory and currentInventory point to the same object. All the adds and subtracts are really acting on the same value, not two different values, so when we get to the test, it will always be equal. The above code would never work if the objects are mutable. If they are immutable, the adds and subtracts would have to return a result object rather than updating in place, and that would work.

Years ago I used a Fortran compiler where integers WERE mutable. We had a function that accepted several parameters, one of them an integer. In some rare cases, the function updated the integer. Then one day someone wrote a call to this function passing the constant "2" as the integer. The function decided to update the parameter, thus changing the "constant" 2 to 1! Every other place in the program that used a constant 2 now mysteriously got the value 1 instead. This took a long time to debug.


It's not a concept that can be usefully explained with examples. The advantage of immutable objects is that you know their data cannot change, so you don't have to worry about that. You can pass them around freely without having to remember whether a method you pass them to could change them in a way your code is not prepared to handle. That makes working with immutable data easier.

With multiple threads, this advantage is just more important because bugs based on multiple threads changing data in ways it's not supposed to be changed are usually not reproducible - they depend on timing and thus sometimes happen and sometimes not, which makes them very hard to analyze and fix.


As you already know, it's a great pattern for multithreading.

It also means much better encapsulation. You can pass those objects around and share them and you never, ever have to worry that someone changes your object's state.

There are some great examples in Java core library. Number subclasses are one, but I think the best example is String. You pass them around, concatenate, get substrings etc. and never need to think about other places. If it was mutable like C/C++ char[], you would always need to keep that in mind.

For the same reason it also leads to more readable and maintainable code. No need to care about other users of the object.

Both these reasons lead us to another important pattern called Value Object. In brief, it makes sense when you care about some particular value (a date, a number, a string, an interval, money, or some slightly more complex objects if you need), but the value itself has no identity, i.e. it has exactly the same meaning regardless of context.


As Java returns by value (i.e. object references are returned from methods), if for example I return a String like so:

private String myString = "foo";

public String getString() {
    return this.myString;
}

and the String class wasn't immutable, then the caller of getString() could modify myString, which may not be the desired behaviour; other parts of the system might not want or expect myString to change. So the caller can only change the object which myString points to, not myString itself.


It's kind of tautological, but the main advantage of immutable objects is that they can't change. When objects can change, you have to think about what might happen with them. You have to think about how, when and why you want to change them. You have to think about what other code in your application might have access to the same object, and what it might change without you knowing. Immutable objects effectively reduce the number (and granularity) of "moving parts" you have to juggle in your system and make your life easier.


Immutable objects are useful when objects are generally shared - not just with threading, but in single-threaded programs also where an object has many clients.

For example, String is probably the most used immutable object in Java. It's immutable to stop users of that string from changing it's contents. If String was mutable, it would mean each user would have to create a unique copy of that string to ensure no-one else was changing it.

Immutable data also has security implications. For example, a security token associated with a user should be immutable, otherwise a rogue program could easily change the user associated with that token.


The main idea here is to make your classes thread safe by using immutable objects. I think this article is a good read on this.

Hope this helps!


A good example is the String class:

A good summary of reasons for immutable objects can be found here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜