Has java – Clone () really been used? How about defensive replication in getter / setter?

Do people almost always use defensive inhalers / installers? For me, 99% of the time I intend to take the object you set in another object as a copy of the same object reference, and the changes you intend to make to it are also made in the object it sets If you set date (date DT) and modify DT later, who cares? Unless I want some basic immutable data beans, it has only primitives. It may be as simple as date. I never use it

In the case of cloning, there is a problem with the depth or lightness of the copy, so you know what kind of "danger" occurs when cloning objects I think I only used clone () once or twice, that is, to copy the current state of the object, because another thread (that is, another HTTP request to access the same object in the session) may be modifying it

Editor – my comments below are more questions:

But then again, you did change the date, so it's your own fault, so the whole discussion term "defense" If you control all the application code in a small and medium-sized developer group, is it enough to record only your classes as an alternative to making copies of objects? Or is this not necessary because you should always assume that nothing is copied when calling setter / getter?

Solution

Effective Java from Josh Bloch:

Item 24: Make defensive copies when needed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>