Deal of the Day

Home » Main » Manning Forums » 2003 » Bitter EJB

Thread: What is defensive copy?

Reply to this Thread Reply to this Thread Search Forum Search Forum Back to Thread List Back to Thread List

Permlink Replies: 1 - Pages: 1 - Last Post: Apr 28, 2004 8:46 PM by: erjablow
Li Xin

Posts: 1
Registered: 3/18/04
What is defensive copy?
Posted: Mar 18, 2004 6:54 AM
  Click to reply to this thread Reply

Hi!

In page 62, last paragraph, it says:

The bean's implementation creates defensive copies for variables.

What does this defensive copy mean?

Thanks.

erjablow


Posts: 9
From: Herndon, VA
Registered: 4/27/04
Re: What is defensive copy?
Posted: Apr 28, 2004 8:46 PM   in response to: Li Xin in response to: Li Xin
  Click to reply to this thread Reply

Here's an elementary non-EJB example. Suppose you have a simple naive JavaBean:

public class Person {

// Constructors skipped.

private String name; // Accessors skipped.
// Name is not a problem anyway,
// as Strings are immutable.
private Date birthDate;

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public Date getBirthDate() {
return birthDate;
}
}


Now, use this class:


Person eric = ...
Date today = new Date();
eric.setBirthDate(today);


The Person eric's birthday refers to the same data as the variable today. If somebody does something malicious like:


today.roll(Date.MONTH, 1);


this will change the Person eric's birthdate. Do you really want this to happen? The common fix is:

public void setBirthDate(Date birthDate) {
this.birthDate = new Date(birthDate.getDate());
}

// Why clone here but not in the set method?
// It's a security issue. Read Bloch,
// Effective Java.
public Date getBirthDate() {
return (Date) (birthDate.clone());
}


But, if this were a Remote EJB reference, then the EJB will have been serialized, sent across the network, and deserialized on the client's machine. Changing the today variable on the server will not affect the EJB on the client's machine, and the fix is unnecessary.

Local references need the defensive copy, while remote references don't. However, it's hard for the bean writer to tell which interface is being used. EJB containers often try to optimize away the serialization too.
So, how do you write efficient Entity EJBs? That is what the authors were discussing.

Respectfully,
Eric Jablow

Legend
Gold: 300 + pts
Silver: 100 - 299 pts
Bronze: 25 - 99 pts
Manning Author
Manning Staff
Manning Developmental Editor