Re: mutate an object or create a new one?
Hi,
concerning your problem of recycling objects, my opinion is clear:
Do NOT recycle objects. It *may* speed up you app in some cases (while
it may slow down your app in other cases). Write clean and readable code
and choose the right data structures and algorithms. If your platform
does not have enough resources to properly run your application,
recycling objects will not help very much. In 99% there are more
disadvantages than advantages.
To your other question ("const" (which I am missing as well) vs
"mutability"):
I have not tested it in a productive environment, but an approach would
by something like that:
class UnmodifiableInt {
protected int i;
public int getValue() {
return i;
}
}
class ModifiableInt extends UnmodifiableInt {
public void setValue(int i) {
this.i=i;
}
}
Then, you can do the following:
class Foo
{
void bar1(ModifiableInt i)
{
}
void bar2(UnmodifiableInt i)
{
}
void bar()
{
UnmodifiableInt ui = new UnmodifiableInt();
ModifiableInt i = new ModifiableInt();
bar1(ui); // compiler error
bar1(i);
bar2(ui);
bar2(i);
}
}
For "plain" objects (in contrast to "compound" objects) this should work
easily.
Of course it is not "save" because if you have a reference of type
UnmodifiableInt, it may point to an object of type ModifiableInt, so
that you could do a cast. But on the other hand, casts are always
somehow "unsafe"... (IIRC its the same with 'const' which you can "cast
away")
On the other hand, even immutable Types like java.lang.String can be
modified (using reflection).
Ciao,
Ingo