tags:

views:

340

answers:

3

I have a factory class that populates objects with data. I want to implementing saving from the object, but do not want to populate the object with db stuff - is it stupid to have my Factory that creates the class also save the data?

ie: in my .Save() method on the object i would call Factory.Save(myObject);

+2  A: 

No, it's not stupid at all, in fact, that's the way how everybody should do it. Business object shouldn't contain any persistence logic.

Btw, if you're using C# 3.0, then you might not even bother with Factory class. Just create extension methods. That way you can still have your persistence code isolated from business object and still be able to call myObject.Save().

lubos hasko
You got a vote up for the first line alone....I've been trying to convince people of that for a long time now.
ckramer
Just don't call it a factory afterwards - you'll start confusing people who knows what a factory is.
jop
+5  A: 

The factory class is a creational pattern that helps with creating new objects.

There are various patterns which deal with persisting objects, one of which is data mapper http://martinfowler.com/eaaCatalog/dataMapper.html

This is often used in conjection with Repository http://martinfowler.com/eaaCatalog/repository.html

You can use these patterns to abstract the database away from your domain/business objects, and access them from within your application to query and save objects.

So the data mapper/repository is responsible for both aspects of persistence (populating from database, and saving back to database).

Keith Patton
+2  A: 

If you are concerned about database stuff in classes - have you considered using O/R mapper?

This would keep the database stuff entirely out of your code and your domain objects clean.

Maybe take a look at NHibernate or Active Record.

Fionn