Taylor Handy
Taylor Handy

Reputation: 93

How should I separate the view of a domain from the domain model itself in java?

How can I decouple how (or even if) a domain model is viewed from the implementation of the view itself. As an example consider the following code:

public class Student
{
    private Set<Course> enrollment;
    public void enroll(Course c){
        // domain implementation
    }
    public void unenroll(Course c) {
       // domain implementation
    }

}

This is a pretty simple example, but it's fine for what I'm asking. What would be a good way of ensuring that the view of this object is decoupled from the actual domain functionality? For example this student should be able to be represented in XML, JSON, or even some sort of game, or not have a view of any kind.

Some of the approaches I've thought of could be something like:

@XmlRootElement(name="student")
public class StudentXmlView implements XmlView<Student> {

    @XmlElement(name="enrollment")  
    private XmlVeiw<Set<Course>> enrollmentView;
}

Would this sort of approach be suitable, or is there some best practice that is typically used in java for separating domain from it's view?

Upvotes: 0

Views: 78

Answers (1)

Constantin Galbenu
Constantin Galbenu

Reputation: 17693

The CQRS architecture is perfect for this kind of separation: it separates the write model (the Aggregates in DDD) from the read model.

The write model is specially designed to protect the business invariants regarding state changes. It executes commands. It cannot be queried.

The read model is designed to be fast and fit for a particular use case. Each use case has other read model. Here you can use whatever technology is best suited.

There is no equality between the write and the read models. You could have 3 write models and 1 read model, or any combination.

In a microservice architecture, each model (write or read) can be a microservice.

The next thing after CQRS is Event sourcing.

Upvotes: 2

Related Questions