views:

150

answers:

4

This might be on the "discussy" side, but I would really like to hear your view on this.

Previously I have often written data access classes that handled both reading and writing, which often led to poor naming, like FooIoHandler etc. The rule of thumb that classes that are hard to name probably are poorly designed suggests that this is not a good solution.

So, I have recently started splitting the data access into FooWriter and FooReader, which leads to nicer names and gives some additional flexibility, but at the same time I kind of like keeping it together, if the classes are not to big.

Is a reader/writer separation a better design, or should I combine them? If I should combine them, what the heck should I name the class?

Thanks /Erik

+2  A: 

ORM might be your best solution.
Or use a repository type pattern, with a "thingContext" object that is responsible for state persistence.

Personally, I use the activeRecord pattern, where save logic is baked into a base class, but I'm leaving it in favor of an nHibernate style repository pattern. The allowance for DDD and testing things without a db is very nice to have in a framework type situation, where my business logic is now gaining traction for a new UI.

DevelopingChris
+2  A: 

I am now using Linq to Sql. This solves the problem entirely.

However if you do not have that option (or some similar ORM tool), I don't see any reason to separate Read/Write methods. It just adds more classes and complicates data access. I have always designed it as follows:

  1. Component/Business Object: Car
  2. Data Access, containing static Read and Write methods: CarDB

Example Usage:

Car car = new Car();
car.Manufacturer = "Toyota"
car.Model = "Camry"
car.Year = 2006;
car.CarID = CarDB.InsertCar(car)
car.OwnerID = 2;
CarDB.UpdateCar(car);

This also makes sense for data access where both Reads and Write need to be performed as part of the same transaction. If you split up the classes, where would that go?

Yaakov Ellis
+2  A: 

Ignoring ORM (not because I'm either for or against it) I would keep them in the same class. They are both facets of a single responsibility and separating them just makes you look in two places where I can't really think of a good reason you would want to do that.

Phil Bennett
A: 

When given the choice I generally subclass the reader to create the writer.

Greg Dean