0

I am constructing an object using data from 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.

rogermushroom
  • 5,486
  • 4
  • 42
  • 68

2 Answers2

2

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.

Matt Bishop
  • 1,010
  • 7
  • 18
  • 1
    I am with you on not performing heavy logic in the constructor but the custom constructor arguments could quickly get messy – rogermushroom Mar 24 '11 at 20:14
  • Many developers create one large constructor that represents all internal fields, and many create numerous special-purpose ones. Having one or more special-purpose constructors tends to show a usage pattern since you can trace that specific constructor through your code. – Matt Bishop Mar 24 '11 at 20:16
  • If the number of fields becomes oppressive, Joshua Bloch recommends the Builder pattern. – duffymo Mar 24 '11 at 22:26
  • So I trust from this you don't think much of the active record pattern – rogermushroom Mar 24 '11 at 22:32
1

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • But then do you not require some sort of DAO service object with heavy logic performing the leg work for the domain object? Also you need to have all these setters in your class just to set persisted values, this may obstruct other more genuine setter methods – rogermushroom Mar 24 '11 at 20:05
  • What heavy logic? "SELECT * FROM FOO"? Where's the logic? ORM solutions can do field access, so setters aren't needed. – duffymo Mar 24 '11 at 21:35