Constructor Design

R

Randy

Hi,

I have a class that needs to retreive data based on a id passed to.
Currently, I have designed the constructor to take the id as a parameter and
then connects to my DAL which retrieves data from my db. Is this good
design?

Thanks
 
P

Peter Duniho

Randy said:
I have a class that needs to retreive data based on a id passed to.
Currently, I have designed the constructor to take the id as a parameter
and then connects to my DAL which retrieves data from my db. Is this good
design?

That depends on whether your class is supposed to represent a single data
object connected to the ID. That is, it's technically possible to add
something to the class so that you can alter the ID and retrieve a different
data object, but IMHO if you find yourself doing that, then including the ID
as part of the object construction sort of breaks the logical abstraction
that your class theoretically represents.

That said, it's not a black and white issue. If you prefer an optimization
in which you construct the object with the initial ID already in place,
there's nothing technically wrong with that. I just think it devalues the
abstraction the class gets you in the first place.

If the class will ever only be used to retrieve that one data object
connected to the ID, then yes...I think it makes a lot of sense to pass the
ID into the constructor. In that case, passing the ID reinforces the
abstraction being used, rather than weakening it.

Pete
 
B

Brian Gideon

Randy,

Well, if you take the advice of the Framework Design Guidelines book
literally then no, it would not be a good design. The authors say to
do minimal work in a public constructor. I happen to apply that rule
more literally than most because I see no compelling reason not to. If
the semantics of the object require that it always be in a state that
is derived from a database call then create a static factory method on
the class that returns such an object. You can give the factory method
a name that implies that a call to the database is occurring (ie. Load,
Fetch, Select, etc).

Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top