Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Are playing cards and dice immutable?


I find it reasonable that a Die is mutable. Each time we toss it we change/mutate its state.

I do not think it is justifiable to have a mutable Card class. It would be strange - and against our intuition - to change the suite or value of an already existing card. The state of a Card is never changed.

In the code, mutability reveals itself by assignments to the instance variables in the bodies of methods.

Why is it natural to use structs for immutable objects and classes for mutable objects?

Classes are reference types. There are often several references to the same objects (this is called aliasing). If the state of the object is update/mutated it can be observed via all the references. Instances of classes are only copied on demand (for instance via Clone or via use of a copy constructor). In your client program you need to be aware of this. Due to aliasing via references, the copy of an object cannot always be used in place of the original object! The identity of class instances are strong.

In contrast, structs are value types. Instances of structs are copied a lot - by assignments, parameter passing, and by return. A copy of a struct instance is just as good as the original. In your client program, you should not notice if you deal with the original struct instance or a copy of it. Mutation is dealt with by creating a "mutated copy". The identity of struct instances are weak.

If you want to mutate an object you should be very conscious about making copies of the object. Such consciousness can be handled with classes, but not with structs.