Re: mutate an object or create a new one?
"Ingo R. Homann" <ihomann_spam@web.de> wrote in message
news:453f0bb1$0$30329$9b4e6d93@newsspool1.arcor-online.net...
Hi,
Oliver Wong wrote:
The problem with the 2-class design is that it fails the IS-A test of
inheritance: that is, it should not be the case than a ModifiableInt IS-A
UnmodifiableInt. So you should not be able to use a ModifableInt anywhere
an UnmodifiableInt is expected.
No, I think, the 2-class-design is better:
Consider you have a method that wants to indicate that it does not change
the Parameter:
void foo(UnmodifiableInt i) {...}
Now, why should it be impossible to pass a ModifiableInt to that method?
It depends on the situation, of course, but what if foo, for example,
uses i as the key in a hashtable, on the assumption that the hashcode for i
will never change. Then passing in a ModifiableInt might cause a lot of
problems.
You could simulate your intended behaviour in the 3-class (or
2-class+1-interface) design as:
void foo(Int i) { ... }
Where Int is the interface/class which only has the getter, but makes no
guarantee about whether or not i is immutable. I.e. you could pass
ImmutableInt or MutableInt to foo, because both classes implement/extend
Int.
And vice versa: Consider a method is returning an ModifiableInt:
ModifiableInt foo() {...}
Why should it be impossible to assign the returned value to a variable of
type UnmodifiableInt to document that the variable will not be modified?
Similarly, you could assign this to a reference of type Int if you don't
care about modifiability.
However, I realize now that I had assumed "unmodifiable" was synonymous
with "immutable", but Chris' and Niklas' posts indicate that some
programmers may interpret a difference between these two terms.
- Oliver