views:

138

answers:

6

Hi,

Is it acceptable for interfaces to declare properties instead of methods?
Which is more preferred?
interface ITaggable { string GetTag(); }
or
interface ITaggable { Tag {get;} }

Living in the .Net world.

Kind regards,

+2  A: 

It's perfectly ok to use properties for that sort of scenario. I prefer using a property as opposed to a GetFoo() method when you really are just getting a value.

AgileJon
+2  A: 

Properties are definitely preferred in this case.

Otávio Décio
A: 

Where the intended implementation language(s) support properties, it's perfectly correct to use them in your interface(s) as well (of course you'd have to stick to getter/setter accessors if your intended target was a language that's lacking in support for properties).

Alex Martelli
A: 

I believe if you will try to declare a read-only property (even without the private setter) the compiler will advice you to use a method instead.

As for the real choice, it is a matter of a particular situation, your coding style and the design approach you are following.

User
+7  A: 

Absolutely. Use a property in an interface exactly as you would in a class.

Examples in the framework include IEnumerator<T>.Current and ICollection<T>.Count.

Jon Skeet
+1  A: 

The usual distinction (at least the one I use, I really hope it is "usual" :)) between properties and methods still apply.

If the act of getting data from the object through a named identifier (property or method) is either:

  • An expensive operation (ie. it might query a database)
  • or an operation that has side-effects (ie. it might change an internal field)

... then it should be a method.

If the operation is light-weight, without side-effects, it can be a property.

So reading the name of a person is a property, since that value should probably be in the object to begin with.

However, to figure out how many orders he has in the system, that should probably be a method, since it will likely have to do a more expensive operation.

At least this is the criteria I use.

And whether it is a class or an interface makes no difference to me in this respect.

In your specific case, I'd go with the property. A "taggable" item should know its tag(s).

Lasse V. Karlsen