Does “Save” method belong to the Business Domain E

2019-06-20 08:05发布

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)
        {
        }
}

2条回答
可以哭但决不认输i
2楼-- · 2019-06-20 08:32

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.

查看更多
疯言疯语
3楼-- · 2019-06-20 08:46

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.

查看更多
登录 后发表回答