开发者

Should an object set its own attributes within the constructor?

I'm wondering in general terms whether an Object should se开发者_Python百科t itself based on one parameter in the constructor. For example: If in the constructor you specify the objects ID, should the object itself then set its own variables by fetching the other data from the database? Or, should another class be created explicitly for creating this object, which would then hide the database from the object.


Here are my recommendations

  1. Use an ObjectFactory pattern to this construction based on an ID. Anything that starts to resemble a recipe, an ObjectFactory patterns works best.

  2. I don't suggest using a dependency on a database inside a constructor of an Object. You can put this data loading logic in the ObjectFactory as well.

Basically, I feel that the implementation of a class should be as lean as possible.


Another class should probably instantiate the Object by reading the values needed to create it from the database. This is a better separation of concerns. The Object which holds the values would probably just be a JavaBean i.e. value holding object. I certainly wouldn't add database access code to individual objects.


Depends on the scenario. But as a rule of thumb, you should try to separate access to database from the object. Personally, I would probably go with a builder class, that has an injectable interface for database access, and would return/build me an object.

Please note, there are many scenarios where it'll be fine to let the object create itself.


If it's sufficiently complex, you could look at implementing a Factory (http://en.wikipedia.org/wiki/Factory_method_pattern).

I believe that is probably what you were describing in your post with 'another object' that helps in the creation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜