In android.os.Message, there are a lot of fields for another thread to identify what to do after receiving a message.
public int what;
public int arg1;
public int arg2;
However, if we change the value in the fields after putting the message into the message queue, it’d affect the way the receiver thread handles the message.
Why doesn’t Android team make android.os.Message immutable?
I think it’ll prevent the Android developers to make mistakes.
Isn’t it a better design to make it immutable?
I have no exact answer for first question (only android team has one). Looks like, it’s related to some memory/performance considerations. Generally, creation of objects are quite expensive, so, Android suggests :
If You follow android reference and use Message.obtain(), you won’t spent time and memory on creation new Message objects, but will re-use existing ones from the ‘message query’. I believe Message was made mutable, because Android is for mobile systems with restricted resources (not sure if it’s valid point today, but it was some years ago).
The same time immutable objects have many advantages. Check out Effective Java Item 15: Minimize mutability for more details. Main reasons for using immutable classes are:
Effective Java mentions only single disadvantage of immutable classes: they require a separate object for each distinct value.