DDD and the use of Getters and Setters

血红的双手。 提交于 2019-12-04 02:31:07
Magnus Backeus

Well, this is a classic discussion. There are several other threads here in Stack Overflow about this.

But. Get/Set's (Auto Properties?) are not all bad. But they tend to make you construct your entities as "dead" data containers that only have prop and not methods. The signs of this is often called Anemic Domain - and have very little behavior. My recommendation is:

  1. Try to use prop as little as you can.
  2. Try to find groups of data that belongs together and SHOULD be together like ex. Firstname Middlename and Lastname. Another example is Zipcode, City, Street. These data is better to set through a method. It minimizes the chances for your entity to be invalid.
  3. Often data that belongs together can be grouped as a Value object.
  4. More Value objects tend to bring out more descriptive methods from your entity that are "Verbs" instead of your usually "Nouns" entities.
  5. More methods for your value objects also opens up for adding more behavior and maybe reducing your "Fat" services (maybe you don't have services with too much leaked business logic...).

There are more to say here... but a short answer. About setting data in constructor: I only do that if this entity cannot "live"/exist without that data. For entity Person I would say that Name maybe isn't that kind of important. But Social Security Number may be a candidate for constructor data. Or entity Employee must have Company in constructor, simply because an employee must belongs to a company.

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