java: advantages of immutable objects in examples

2020-03-04 08:33发布

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

8条回答
虎瘦雄心在
2楼-- · 2020-03-04 08:59

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.

查看更多
我命由我不由天
3楼-- · 2020-03-04 09:02

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.

查看更多
4楼-- · 2020-03-04 09:03

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.

查看更多
爷、活的狠高调
5楼-- · 2020-03-04 09:03

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.

查看更多
欢心
6楼-- · 2020-03-04 09:03

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.

查看更多
我想做一个坏孩纸
7楼-- · 2020-03-04 09:06

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!

查看更多
登录 后发表回答