Sunday, July 02, 2006

Java Practices: Immutable objects

Defensive copying. Just like defensive driving, can save you from a major head break.

You really have to stick this in your head. Parameters being passed or returned from methods. Else you suddenly have unpredictable objects acting more strangely than the last zombies from the resident evil movie.

There is a big difference between:

public Date getDateOfDiscovery() {
return new Date(fDateOfDiscovery.getTime());

and the wimpy version of above:

public Date getDateOfDiscovery() {
return fDateOfDiscovery.getTime();

And likewise should always remember that "setters are evil (tm)".


You have a domain object named account. And naturally you want to do insert some good old strategy pattern to implement the behaviour of your debit method. So that you have:


Which encapsulates all the technical wizardry known to man to securely do a debit transaction. After which, it stores it to a transaction table associated to your account object.

Now if you have a setter for that transaction table like:

account.setTransactions(Set _transactions).

The crooked descendant of green lantern coder can just as easily do something with the transactions table without going thru the carefully crafted debit function mentioned previously.

So thats our lesson for today, Defensive Copying, and Setters are Evil.

- (bitten by the un-defensive copying bug...)

No comments: