2

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.)

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279

2 Answers2

6

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Good point about the side-effects. So far that hasn't been an issue, but it's definitely something for myself and other developers on the team to keep in mind. As soon as a property "does something" other than simply return a description of the current state of the object, it should be a method. – David Dec 13 '10 at 14:11
  • @David: Well, it depends what it does. It could potentially change a cached value... or log what it's doing. But making *visible changes* to state would be a bad idea. – Jon Skeet Dec 13 '10 at 14:14
4

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