Defensive copy from Effective Java

后端 未结 5 986
庸人自扰
庸人自扰 2020-12-15 19:06

I am reading \"Effective Java\" by Joshua Bloch, item 39 make defensive copy, and I have some questions. I always use the following construct:

MyObject.getSo         


        
5条回答
  •  醉梦人生
    2020-12-15 19:40

    Defensive copy is a good idea, but you need to understand when and where it gets used. If the web of objects you are manipulating is internal, and it not intended to be thread safe, then the defensive copying is being mis-applied.

    On the other hand, if this is web of objects that are getting exposed publicly, then you are at risk of violating Law of Demeter. If so, consider exposing a manipulator API on your myObject.

    As a sidenote, your code sample made the getSomeRef look like a static API. I would suggest that you name any static API that returns a copy of some singleton accordingly (e.g. copyOfSomething()). Similarly for a static factory method.

提交回复
热议问题