DDD and the use of Getters and Setters

2019-04-05 12:42发布

问题:

I've read a few articles/posts regarding the use of Getters and Setters, and how they help to defeat the purpose of encapsulation in domain model objects. I understand the logic behind not using setters - you are allowing client code to manipulate attributes of that object, outside the context of the object business rules and invariants.

Now this principal does still confuse me. For example, what happens if I need to change the value of a member variable of an object? For example, if the name of a person changes how can I reflect this in the model? At first I thought, well why not have a function called 'ChangeName' which let's me pass in the new name and it in turn can change the internal 'name' variable. Well.... that's just a setter isn't it!

What I need to clarify - if I were to completely eliminate setters, then in situations such as the above, am I supposed to solely rely on constructor parameters? Should I pass the new attribute value in place of the old attribute value via a constructor, after which I can persist the changes by passing the object to whatever persistence infrastructure I have?

These two articles are useful in this discussion:

  1. http://kellabyte.com/tag/ddd/
  2. http://typicalprogrammer.com/?p=23

回答1:

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.