I ran into something tricky today. I have a domain object.
public class User {
private String firstName;
private String lastName;
// getters and setters
// a utility method
public String getFullName() {
return this.lastName + ", " + this.firstName;
}
}
Everything looks reasonable except the full name is always "null, null" at runtime. Then I realized Hibernate has lazy loading. "this.lastName" and "this.firstName" are not populated until the getter methods are called. It worked fine after switching to getters.
public String getFullName() {
return this.getLastName() + ", " + this.getFirstName();
}
The encapsulation forces you to user getters outside User class. However, it turns out that in this case, I'd better stick to getters instead of "this." accessor anywhere even inside the User class.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment