Why is TaskRepository defined in service layer and not in domain layer? #268
-
You define the TasRepository here in the service layer. I am curious why did you make that decision? I am new to DDD but I think it's a better idea to put the interface of the repository in the Domain layer so that business logic can be built on top of the functions defined in the repository. Here is a quick example. Imagine a user is only allowed to create 5 tasks per day. That's a business rule which should be enforced in the Domain layer. In order for the Domain Model (Task) to check if 5 tasks were already created it has to make a look up in the database. This functionality can be provided by the repository. type Task struct {
Description string
}
func (t *Task) NewTask(ctx context.Context, description string) (Task, error) {
if assertTaskLimit(ctx, date.Now()) != nil {
return Task{}, error.Error("task limit reached already"
}
return Task{Description: description}, nil
}
type TaskRepository interface{
assertTaskLimit(ctx context.Context, date datettime) error
}
Here is another link to stack overflow about where to put the repository. Most answers suggest to put the interface of the repository in the domain layer. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The code you're suggesting won't work because the method in the interface is unexported, see this playground; to make it work make that method exported by changing With that being said what you're describing is a So how can we enforce that rule? One way would be to define a However keep in mind that although edit: typo |
Beta Was this translation helpful? Give feedback.
The code you're suggesting won't work because the method in the interface is unexported, see this playground; to make it work make that method exported by changing
assertTaskLimit
toAssertTaskLimit
; also notice the new change whereUser
is the one owning tasks notTask
so this method(t *Task) NewTask
aligns with the problem you described originally.With that being said what you're describing is a
User
rule not aTask
rule; yesTask
may have rules as well, like no emptyTask.Description
for example, but it's theUser
type that owns "no more than 5 tasks a day".So how can we enforce that rule? One way would be to define a
User.Validate
method that does that, it makes sure the tasks for …