Separate read and write data access class or merge them?

It may be on the “discussed” side, but I would really like to hear your opinion about it.

Earlier, I often wrote data access classes that processed both reading and writing, which often led to a bad name, for example, FooIoHandler, etc. The rule of thumb that classes that are difficult to name is probably poorly designed suggests that this is not a good solution.

So, I recently started sharing data access in FooWriter and FooReader, which leads to nicer names and gives additional flexibility, but at the same time I kind of support them together if the classes are not big.

Does the reader / writer share the best design, or should I combine them? If I have to combine them, then what the hell should I call a class?

Thanks / Erik

+4
source share
5 answers

ORM may be your best solution.
Or use a repository type template, with a thingContext object that is responsible for maintaining state.

Personally, I use the activeRecord template, where the save logic is baked into the base class, but I leave it in favor of the nHibernate style repository template. Accounting for DDD and testing things without db is very nice to have in a situation like a framework where my business logic is now gaining ground for a new user interface.

+2
source

Now I am using Linq for Sql. This completely solves the problem.

However, if you do not have this option (or any similar ORM tool), I see no reason to separate the read / write methods. It simply adds more classes and complicates data access. I always designed it as follows:

  • Component / Business Object: Car
  • Data access containing static read and write methods: CarDB

Usage example:

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

It also makes sense to access data, where both read and write must be performed as part of the same transaction. If you separate classes, where will it be?

+3
source

Ignoring ORM (not because I am either for or against it), I would save them in one class. They are both aspects of the same responsibility, and sharing them just makes you look in two places where I cannot think of a good reason that you would like to do.

+3
source

Something that reads and writes to the backend storage can be called a data access device, or ReaderWriter, or IO, or Store.

So, what about one of:

  • FooDataAccessor
  • Fooaccessor
  • Fooreaderwriter
  • FooRW
  • Fooio
  • Foostore
  • Foostorage
+1
source

When choosing an option, I usually subclass the reader to create an author.

0
source

Source: https://habr.com/ru/post/1276445/


All Articles