0

I have doubts about where I should check my invariants...

For example, I have a Question aggregate with the following invariant:

  • The question's text must be not null
  • The question's text must have a length between 100 and 500 characters

I have read that the best place to check the invariants is in aggregate's constructor, but I have also read it would be recommended push domain logic in value objects, for example.

A possible aggregate's implementation could be:

public class Question {
  private final id: QuestionId;
  private final text: QuestionText

  public Question(id: String, text: String) {
    // verify invariants
    ensureLengthText(text); // this method verifies the invariant    

    this.id = new QuestionId(id);
    this.text = new QuestionText(text);
  }
} 

QuestionId and QuestionText are value objects.

In this case, in the aggregate we can see the invariant explicitly.

But, if we push that invariant logic in QuestionText value object, in the aggregate we will not see that invariant... then, what would be the best approach?

1 Answers1

1

If you can easily enforce an invariant (e.g. "Question texts cannot be shorter than 100 characters nor longer than 500 characters") in a value object, I recommend doing so. Question inherits that invariant (and any and all others from QuestionText) by saying that text is a QuestionText.

Levi Ramsey
  • 18,884
  • 1
  • 16
  • 30