Java – Separating Read / Write Responsibilities of a DB

javaobject-oriented-designprogramming practices

We're working on a reporting system which has a clear write and a read path. For example writes will only happen after consuming events from a queue and reads will only happen when serving requests from an API. The responsibilities won't likely mix, i.e. the service writing to the DB won't use the queries used by the API and vice versa.

The code is really long (cause java) and could be confusing to a new person. I was thinking of separating the DB into two classes, ReportingIngestDBClient vs ReportingReadDBClient not married to the names.

I was wondering:

  • 1) Has anyone followed this pattern? Did it make things more or less clear? If so what names did you use?

  • 2) If you didn't follow the pattern of creating 2 separate objects to handle different queries, do you have a strong opinion against it and why?

Best Answer

As Laiv put in his comment, you should look at CQRS design pattern. And let me expand on it here.

CQRS stands for Command Query Responsibility Segregation. The fundamental idea is to divide your data access code into two sharply separated categories:

Queries: Return a result and do not change the observable state of the system (are free of side effects).

Commands: Change the state of a system but do not return a value.

Here are a few articles to get you started on CQRS design pattern:

  1. Martin Fowler - CQRS
  2. Greg Young - CQRS, Task Based UIs, Event Sourcing agh!
  3. Udi Dahan - Clarified CQRS
Related Topic