Mutable vs. Immutable with business logic objects
A lot has been said about mutable / immutable objects in the data model.
But what about the business logic? For example: a CD player. One class is responsible for playing the CD.
// Immutable version:
class Player
{
CD cd;
public Player(CD cd) { ... }
}
// Mutable version:
class Player
开发者_C百科{
CD cd;
public void ChangeCD(CD cd) { ... }
}
I can think of several subtle advantages and disadvantages to both versions. For example, when player is mutable, other objects can take the player and it stays valid even if the CD changes. When player is immutable, you need a wrapper object (e.g. Command Pattern) that gets updated when a new Player is created.
Which version is preferable in which cases? Are there any general guidelines?
Here's a third option.
class Player
{
// private CD myCD <- no private field for the CD
public Player() {}
public void playCD (CD cd) {}
}
A player should never own a CD object. It should just be told here is a CD object, play it.
A better option would be
class CDPlayer : DataPlayer
{
public Player() {}
public void playData (IData cd) {}
}
class CD : IData {}
If you reduce the amount of coupling between your CD and Player then you really don't have to think too hard about this.
I believe your example is a bit flawed with respect to your actual question.
精彩评论