开发者

Domain objects encapsulation: static methods vs Service classes

开发者 https://www.devze.com 2023-02-07 00:23 出处:网络
I\'ve read in DDD book (Eric Evans) that procedures which require to be used in presentation should be moved to services classes. For instance BankAccountManagementService has ChangeBankAccount, GetBy

I've read in DDD book (Eric Evans) that procedures which require to be used in presentation should be moved to services classes. For instance BankAccountManagementService has ChangeBankAccount, GetByAccountId ... methods.

However I need to encapsulate setters of some properties to forbid assigning them from other business objects. As C# doesn't have friendly classes it is impossible to use this type of encapsulation in case of Services. But it is possible to do it using static methods of BankAccount business object.

(1) How do you solve this limitation in case of using Services for mentioned above reason?

开发者_如何学C

Edit: additional question

(2) Why it is bad to use static method instead of services? I can place them in separate partial class file to not mix proc code with Entity code.

Thanks in advance :)


If properties of a domain object should not be set (immutable), then make them private (or protected).

The service method that is responsible for altering the private properties of a domain object would perform necessary validation and or permissions checks and create a new object via one of its constructors (including its id) with the properties it wants to change and save that object.

Another option would be to put a set method on your domain object which takes the new value, and some kind of permission object, or attribute the method to require certain privileges. That way you can constrain where the set is called from.

EDIT: Making things static is an architectural black hole: You cant inherit from them or alter them in any way. It makes it impossible to use dependency injection. Versioning is harder; once you have made then static and the are used, it is hard to reverse that decision. Also, your static method may not use instance data today, but it may need to in the future.

When the methods are instance methods, you can make use of polymorphism and generics, creating a generic ServiceBase class and putting commonly used methods there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号