I know immutable objects are preferred to mutable objects for reasoning and maintenance and... but in occasions making a class immutable have some costs, let me explain it with a simple example:
I have a class which draws a text in a box:
class TextDrawer { public string Text {set; get} public RECT Box {set; get; } public void DrawTextInBox() { } } It is probable that the Text overflows from the box and part of it wasn't written. Now I have two options:
1- Make the TextDrawer mutable and DrawTextInBox a non-pure function and on each call it draws the remaining part of text in the box.
class TextDrawer { public string Text {set {remaining = text = value;} get {return text; }} public RECT Box {set; get; } private string remaining; public void DrawTextInBox() { ... update remaining part; } } 2- Keep the TextDrawer immutable and DrawTextInBox a pure function which returns the remaining part, then the caller should keep track of the remaining and pass it again to the TextDrawer or instantiate a new TextDrawer by the remaining text until there is nothing to write.
class TextDrawer { public string Text {set; get} public RECT Box {set; get; } public string DrawTextInBox() { draw as you can; return remaining; } } The second approach is immutable but actually shifts the responsibility of updating the remaining part outside of the class. The first approach while it is mutable but just need a call to DrawTextInBox to draw the remaining part.
The logic of the above example was simple but note this logic could be more complex, then I don't know to extract this logic from a class in order to make it immutable or let it be mutable and have the logic inside?