开发者

Model.Is___ - Should it be a Property or a Method?

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 persi开发者_运维问答stence 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.)


Assuming that accessing the property:

  • Has no side-effects
  • Is "reasonably speedy" (yeah, very woolly...)

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:

  1. It describes the object in some way, so conceptually its characteristic, its property

  2. It does not ask for any parameters

  3. It basically just retrieves certain data, not performs any standalone actions or modifications

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜