Object-Oriented Design vs. Persistence

From time to time I attend discussions about OOP. Every time someone come up with the argument of dealing with persistence. The typical question can be reduced to should an object persist itself or rather be persisted? I believe the question is fundamentally wrong.


Traditional Approach

Traditionally (and very wrongly) an object is seen as data with a bunch of procedures dealing upon it. A typical school-book code looks like follows:

class Person {

  private String personalId;
  private String firstName;
  private String lastName;

  String getPersonalId() { return personalId; }
  String getFirstName() { return firstName; }
  String getLastName() { return lastName; }
}

How to persist the Person object? One approach is to create a repository:

class PersonRepository {

  void save(Person person) {
    // persist the object
  }
}

Second approach is to let the object persist itself:

class Person {
  // ...

  void save() {
    // persist the object
  }
}

Which one is better? None, or more precisely, depends.

Domain-Driven Design

Domain-Driven Design (DDD) calls for designing objects driven by their business (domain) meaning rather than by technical aspects. According DDD, persistence is just an implementation detail. How this helps us with our dilemma? Actually a lot: the question, where to put the persistence, is driven by the domain as well as all other concerns.

Just listen to the business, what does it say? Is it talking about a register for people registration?

class PersonRegister {

  void register(Person person) {
    // ...
  }
}

Or rather about person reporting, checking in, applying or enrolling?

class Person {
  // ...

  void enroll() {
    // ...
  }
}

Don’t think like a technician: "this object must be persisted", understand the domain and model around it. The domain must be found again in the model.

Because the theory can never know your domain, it’s impossible to create a framework helping to cut the code vertically. All the tool can only help with the horizontal cutting and technical regards, which encourages the implementers to concentrate too much on techniques (like persistence) and forget about the domain. The biggest problem with the blue book I have is that it focuses a lot on tactical design and building blocks like Entities, Services and Repositories. At the end of the day that is the only thing some readers get from the text ignoring the real value: the importance of communication with domain experts and understanding the business being built.

Conclusion

Pure technical concerns like persistence don’t belong to object-oriented design. These are mere implementation details hidden behind APIs. APIs tell the story of the domain. Model the API around the domain, don’t let implementation leak to the API.

Happy designing!