Hibernate design pattern question
Im working with Hibernate. It works great. However, say that I have a class that corresponds to a database table with only getters and setters and toString, equal methods. Now I would like to add some more methods for helping purpose, for example, say that I would like to get the creationdate with some added description text as shown below.
public class Client {
private long id;
private Calendar creationDate;
protected String password;
public long getId() {
return id;
}
开发者_开发知识库 @SuppressWarnings("unused")
private void setId(long id) {
this.id = id;
}
public Calendar getCreationDate() {
return creationDate;
}
public void setCreationDate(Calendar creationDate) {
this.creationDate = creationDate;
}
..
.. some other getters and setters that corresponding to SQL columns
//Here I would like to have some help methods. Is it recommended to put it here?
public String getCreationDateInSecs() {
return "Date in secs: " + creationDate.getTimeInMillis * 1000;
}
}
The question is: Where should I place this method?
Should I add it in the same class as the Value Object or should I place it somewhere else? I would like to know the best practice if you know what I mean =)
Best regards
Bozho basically outlined two possible approaches: rich model and anemic model, and suggested a rich model as more OOPish. I'll advocate an anemic approach here.
The functionality you describe looks like a responsibility of a presentation layer. I think it would be better to put it into UI-related classes rather than into the domain model.
Putting it into domain model looks harmless as long as the logic is as simple as
return "Date in secs: " + creationDate.getTimeInMillis * 1000;
However, imagine that you got an additional requirement to return a localized description. You will have to add dependencies on localization facilities to your domain model, that increases coupling of your code.
So, it's better to keep responsibilities of different layer separated.
Absolutely no problem in adding the method in the entity. It is where it belongs, because it operates on the internal state of the object.
You can make an utility method, like ClientUtils.getCreationDateInSeconds(client)
, but that's rather non-OOP.
If you are concerned about mixing your entities with many methods like this, and you have many DAO methods, you may consider using the Aspect oriented approach.
It will allow you to separate the pure entity stuff, the DAO stuff, and other utility methods in separate "aspects" without breaking OO principles.
Spring and AspectJ does this well. If you want a quick example of how stuff is implemented take a look here: http://static.springsource.org/spring-roo/reference/html/architecture.html
精彩评论