开发者

Should I populate member variables with data from a database in the constructor

开发者 https://www.devze.com 2023-02-20 03:37 出处:网络
I am constructing an object using data f开发者_如何学Gorom a database table by passing the primary key of the row of data I want to use to construct the object.

I am constructing an object using data f开发者_如何学Gorom a database table by passing the primary key of the row of data I want to use to construct the object.

Should the population of the member varibles of this object take place in the constructor or another method called by constructor or somewhere else altogether?

How is this done in a rails ActiveRecord and other ORMs, I suspect there are a set of setters which are called for each field by the framework, but I don't really want a complex framework doing all this so whats good practice to role my own simple mechanism?

Note: Keeping in mind I don't want to be creating a mass of anemic data models which can't manage there own state.


A safety rule followed in many languages and frameworks is to never do dangerous things (read: operations that could throw exceptions) inside a constructor because you don't often have the ability to throw those exceptions or otherwise gracefully respond to them. My recommendation would be to perform your database operations outside of the class, then use a custom constructor that ingests the fields you want in the object. Inside that constructor you will set (via simple assignment) your internal members.


I don't put managing persistence in the anemic category. That belongs in a separate persistence tier. I would not put it in a constructor.

I think anemia results when objects only care about state and don't embed business smarts for manipulating it. Put more thought it that; don't worry about persistence.

0

精彩评论

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