Model.Is___ - 它应该是属性还是方法?
当我为某个域设计模型时,它们几乎总是最终具有一些 .IsSomething
功能。 IsNew
和 IsDirty
常见用于数据持久性目的,IsValid
用于业务规则验证,甚至在当前项目中使用 IsFraudulent
(更多业务规则验证)等。每当我看到其他人实现这些时,它们几乎总是作为方法来完成。但我发现自己想知道这是否有特殊原因。
我倾向于将属性视为描述对象,将方法视为执行某种操作。这些并没有真正执行操作。它们涉及代码,因为它们在调用时是动态确定的,并且它们显然是只读的,但对我来说,它们仍然适合作为属性而不是方法。
我想,属性可能存在序列化问题。尽管丰富的域模型往往无法很好地序列化,因为它包含逻辑和功能,所以每当我需要跨服务边界移动某些内容时,我通常都会首先将其扁平化为定义的 DTO 结构。
但我想知道是否还有其他人对这个主题有任何见解?是否有充分的理由将它们实现为方法而不是属性?
(切线相关,尽管已经给出了答案,扩展属性确实有助于保持诸如我有许多 IsSomething()
扩展方法,通常在 System.String
上,用于实现特定于域的逻辑,但即使属性是可行的方法,我可能想坚持使用方法只是为了与扩展保持一致。)
As I design the models for a domain, they almost always end up having some .IsSomething
functionality on them. IsNew
and IsDirty
are common for data persistence purposes, IsValid
for business rule validation, even IsFraudulent
in a current project (more business rule validation), etc. Whenever I see these implemented by others, they are almost invariably done so as methods. But I find myself wondering if there's a particular reason for that.
I tend to see properties as describing an object and methods as performing some kind of action. These don't really perform an action. They involve code because they're dynamically determined when called, and they're clearly read-only, but to me they still fit as properties rather than methods.
There could potentially be a serialization issue with properties, I suppose. Though a rich domain model tends not to serialize well anyway given that it contains logic and functionality, so any time I need to move something across a service boundary I generally flatten it into a defined DTO structure first anyway.
But I wonder if anybody else has any insight on the subject? Is there a good reason to implement these as methods rather than as properties?
(Tangentially related, though an answer has already been given, extension properties would really help with consistency on something like this. I have a number of IsSomething()
extension methods, usually on System.String
, for implementing domain-specific logic. But even if properties are the way to go, I may want to stick with methods just for consistency with the extensions.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设访问该属性:
那么我认为没有理由不将其设为属性。序列化不应该成为问题 - 大多数序列化方案都提供将属性标记为瞬态(即不可序列化)的方法。
Assuming that accessing the property:
then I see no reason not to make it a property. The serialization shouldn't be an issue - most serialization schemes provide ways of marking a property as transient (i.e. not-to-be-serialized).
我会使用属性,因为:
它以某种方式描述对象,因此从概念上讲它的特征,它的属性
它不要求任何参数
它基本上只是检索某些数据,不执行任何独立操作或修改
I would use a property because:
It describes the object in some way, so conceptually its characteristic, its property
It does not ask for any parameters
It basically just retrieves certain data, not performs any standalone actions or modifications