The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Li Xin (1) [Avatar] Offline
#1
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 (9) [Avatar] Offline
#2
Re: What is defensive copy?
Here's an elementary non-EJB example. Suppose you have a simple naive JavaBean:
[pre]
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;
}
}
[/pre]

Now, use this class:

[pre]
Person eric = ...
Date today = new Date();
eric.setBirthDate(today);
[/pre]

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

[pre]
today.roll(Date.MONTH, 1);
[/pre]

this will change the Person eric's birthdate. Do you really want this to happen? The common fix is:
[pre]
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());
}
[/pre]

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