Defensive copy from Effective Java

后端 未结 5 1008
庸人自扰
庸人自扰 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:32

    I would suggest defining a readableThing interface or class, and deriving from it mutableThing and immutableThing interfaces. A property getter should return one of those interfaces based upon the returned item's relation to the list:

    1. It should return a mutableThing if the thing may be safely modified in such a fashion that changes will be stored to the underlying list.
    2. It should return an readableThing if the recipient of the object cannot use it to modify the collection, but there's a possibility that future operations with the collection might affect the object.
    3. It should return an immutableThing if it can guarantee that the object in question will never change.
    4. If the intended outcome of the method is for the caller to have a mutable thing which is initialized with data from the collection, but which is not attached ot it, I would suggest having the method which accepts a mutableThing from the caller and sets up its fields appropriately. Note that such usage would make clear to anyone reading the code that the object was not attached to the collection. One could also have a helper GetMutableCopyOfThing method.

    It's too bad Java doesn't inherently do a better job of indicating declaratively who "owns" various objects. Before the days of GC frameworks, it was annoying having to keep track of who owned all objects, whether they were mutable or not. Since immutable objects often have no natural owner, tracking ownership of immutable objects was a major hassle. Generally, however, any object Foo with state that can be mutated should have exactly one owner which regards mutable aspects of Foo's state as being parts of its own state. For example, an ArrayList is the owner of an array which holds the list items. One is unlikely to write bug-free programs using mutable objects if one doesn't keep track of who owns them (or at least their mutable aspects).

提交回复
热议问题