Immutable object returned by methid
I have a question about immutability, or at least, a question
about the right way to implement the concept I have in mind.
The folllowing is a distilled example of a more complex problem.
Suppose I have some bean class called Something:
class Something {
private int value;
public Something(int value) { setValue(value); }
public void setValue(int value) { this.value = value; }
public int getValue() { return value; }
}
Now suppose I have a set of business rules I want to
enforce, so I create a class Manager to encapsulate a
Something and enforce those business rules. Just as
an example, let's say the business rule is that the
Something value has to be even, and is bumped by one
if it's not:
class Manager {
private Something managedSomething;
public Manager(Something s) {
setSomething(s);
}
public void setSomething(Something s) {
if (s.getValue() % 2 != 0)
s.setValue(s.getValue() + 1);
managedSomething = s;
}
public Something getSomething() {
return managedSomething;
}
}
Other parts of the application are free to create
and mess with Something objects, and for most of
the application the "even" business requirement
doesn't exist. But for the cases where that
requirement DOES exist, you create a Manager, and
let the Manager manage the Something.
Problem is, clients can change the value and avoid
the business rule via:
manager.getSomething().setValue(21);
Here's where my immutability question comes up --
if manager.getSomething() returned an IMMUTABLE
Something, then all would be well. Is there a
way to make the return value from a method call
immutable?