Does “Save” method belong to the Business Domain Entity?

佐手、 提交于 2020-01-03 09:21:54

问题


I am not using any ORM. So I am having a debate whether "Save" method actually belongs to a Business Domain entity or should be abstracted in some service that will be handed over the Business Domain Entity for saving ?

e.g.

class Employee
{
    string Name;
    DateTime Birth;

    GetAge()
    {

    }

    Save()
    {
    }           

}

OR

class Employee
{   
    string Name;
    DateTime Birth;

    GetAge()
    {

    }


}

SomePersistenceService
{
    Save(Employee emp)
        {
        }
}

回答1:


Since this question is tagged with 'domain-driven-design', you'll need a repository to do it for you.


Just rename SomePersistenceService to EmployeeRepository. So you were on the right track with your second option. "abstracted in some service that will be handed over the Business Domain Entity" is called repository in domain driven design

A repository is a way to pretend that your datastore is a collection. So it has methods like Add and Remove instead of Save and Delete.




回答2:


There's no single best solution, the problem you have stated is the choice between Repository and Active record patterns.

Generally, Repository is more suitable for unit testing, as Repository interfaces are easy mockable, also Repository pattern uses High Cohesion and Single Responsibility principles(it may seem strange from the OOP's point of view that your business entity will contain code for saving itself to the database, transferring itself over the network, or exporting to some XMLs, etc.)

Active Record may provide more speed in RAD development, and some tools like Spring Roo were first designed only supporting Active Record, Repository support was added only recently, as I know. AFAIK Ruby On Rails uses Active record, and some other great tools too.

As for the Domain Driven Design, you should use Repository as Jeroen suggested, because Repository is a basic DDD pattern(it's a domain centric version of DAO pattern), but you should check if your tools have the direct support of either pattern.



来源:https://stackoverflow.com/questions/11613716/does-save-method-belong-to-the-business-domain-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!