Should Transfer Object always reflect the entire DB row entry?
I've got a question on the transfer object in DAO pattern. Let's say you have a USER table, and there are 20 fields in this table. 开发者_StackOverflow中文版In the business logic, I notice that I may need field 1 to field 3 in some scenarios, and field 4 - field 6 in other scenarios. So when I implement the userTO class, should I only define field 1 - 6 only or I should define all 20 fields. Another thing is if I define all 20 fields, the SQL in the UserDAOImpl
class will always need to fetch all 20 fields in order to initiate the userTO object, will that be a issue?
Any suggestions are greatly appreciated. Thanks!
Assuming your userTO class is highly cohesive...
When you create instances of objects you always want to ensure that they are created in a valid state. That is, that you can take an instance of a given object and be able to pass it into a method anywhere in your program without receiving programming error type exceptions (e.g. NullPointerException). This would lead to conclusion that you should always create your userTO with all 20 fields.
However, we live and work within contraints. If having all 20 fields populated in each instance of userTO causes unnecessary and adverse strain on your system then you might want to think about perhaps creating a userTOShort, which contains a subset of userTO fields that are used frequently. Then the "optional extra" fields that are needed very rarely can be populated when necessary. This "short" solution feels a bit dirty but I don't know of a cleaner solution.
精彩评论