Is an object that contains a fixed set of mutable objects mutable?

Mutability still confuses me from time to time.

If I have an object that contains a fixed set of mutable objects. Do you consider this object mutable?

Example: I have an object called Puzzle which containts a fixed set of Pieces. The Pieces are mutable. For example, they can be upsideDown and its orientation can change. Assuming you cannot loose pieces in this example (if only that were true in real life...), I guess the Puzzle object is still immutable, right?


From wikipedia: In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

In your example the Puzzle object is mutable because you can change the state of one of its Pieces.


No. The object would be mutable. An important thing with immutability is that (pure) functions that take the object as a parameter returns the same value each time it is called. This would not be the case if the object contains mutable properties. Consider this example:

A mutable class:

class Counter {
    private int count = 0;

    public int getCount() {
        return count++;
    }
}

An "immutable" class:

class Container {
    private final Counter theCounter = new Counter();

    public Counter getCounter() { return theCounter; }
}

And a seemingly pure function that operates on a Container :

public int getCount(Container container) {
    return container.getCounter().getCount();
}

So, if Container was immutable, you would expect that getCount() would return the same value if the same Container was passed to it twice. But this is not the case.

Container container = new Container();
getCount(container); // Returns 0.
getCount(container); // Returns 1.

No,an object can't be immutable if it contains atleast one mutable object. Here the pieces are mutable. So Puzzle can't be immutable.

If you want to make Puzzle immutable, some how make the pieces immutable according to the requirement.

链接地址: http://www.djcxy.com/p/20798.html

上一篇: 空对象的JSON规范

下一篇: 包含一组固定可变对象的对象是否可变?