Search code examples
domain-driven-designdomain-modeldomain-modelling

How should I use singleton in DDD?


I am implementing a school related app for the local government. I have classes and I want to count grade using the following formula: grade = acedemicYear - commencingYear + 1.

You can model this 2 ways:

  • both commencingYear and academicYear have a Year type and the acedemicYear year is some kind of singleton, so AcademicYear.getInstance() - this.commencingYear + 1
  • another solution that commencingYear has a type of AcademicYear, and I have a Calendar class, which gives me the current year, so Calendar.getAcademicYear() - this.commencingYear + 1

Still I don't feel these right. I am not sure whether I should inject the year into the model or it should be inside the model. Another problem that the academic year should be changed more or less manually, at least it starts every year on a different date. By increasing the academic year the grade > 8 means that the class is finished, so children from that class should not be on the current student list. What do you think, what is the best way to model this?


Solution

  • AcademicYear can of course be a value type like you've done. But isn't that over complicating things?

    If you have an entity type which contains both commencingYear and academicYear you can easily control the value for those fields. Thus if someone tries to enter a date which is out of bounds you can just thrown an exception.

    Regarding the calculation it sounds like business rules and therefore it should be wrapped within a method in the entity or in a domain service.

    i.e. it's a rule, but a rule for a specific entity in the domain. thus it should not be wrapped in a static somewhere but implemented in the correct entity class.

    Writing a more specific answer is hard as I have now knowledge about your domain or how you have implemented it.