Artyom
Artyom

Reputation: 3571

How to use time in DDD?

Consider this use case. A user account is active only at some period of time. And user can't login if it is not active.

I image this. We have a value object, an account end time in an account aggregate. A domain model can't "load" current time (we do unit tests and don't use DateTime.Now). The model is given current time. Then we need to implement the validation in a domain service that would be given current time from OS (or from unit test) and give it to a user account aggregate so that it would tell if account is active or not.

So any time we need to implement a time related logic we need to do a domain service as described. Is it good approach as you see it? Or there is some simpler, better solution?

Upvotes: 3

Views: 1654

Answers (1)

theDmi
theDmi

Reputation: 18034

As others in the comments have suggested, use a service that is able to return the current time. This service can now be replaced in unit tests.

If you do a lot of date / time handling and also have to consider different time zones, I strongly suggest you use Noda Time.

Noda Time is an alternative date and time API for .NET. It helps you to think about your data more clearly, and express operations on that data more precisely.

Noda Time already includes a service interface that returns the current time as mentioned above, see IClock. Whether or not you want to use that interface directly in your domain logic is up to you. But in my opinion date / time handling is basic library functionality, so I usually take a dependency on Noda Time from every project.

Upvotes: 4

Related Questions