My office colleague told me today that is bad practice to use properties in interfaces. He red that in some MSDN article(s), which I couldn\'t find (well I was trying few ti
An interface is a contract for a class to implement and I see no reason why properties should be excluded from such a contract. Furthermore, properties are intrinsic to .NET.
As an example: ICollection<T>
has both Count
and IsReadOnly
.
IEnumerator is a perfect example for scenario where will need property as interface member. How you are going to store Current element if do not enforce implementer to do so?
There is widely recognized term "code smell". I suggest introducing "programmer smell" concept - if someone insists on some rule, but can not explain why - it is a smell. Your colleague should be able to explain why properties in the interface are bad. If he can not - he is probably wrong even if article he is referring to is right.
That article may be was talking about some specific kinds of interfaces, may be it had something to do with COM and interoperability or whatever. Or he may be just got it wrong. Understanding rules and being able to explain them is important part of using rules.
I'll just add my voice in here as well - I've never come across this recommendation. A property is effectively a pair of get/set methods.
Like every other design decision. If it genuintely makes sense; if it is appropriate for the system under design, if it doesn't cause maintenance problems, if it doesn't cause performance problems, there should be no reason you can't do it.
Never seen anything like this per se, but there was some talk a while ago about not using properties in cross-platform interface definitions as there are many platforms which don't support properties, but just about everything supports methods.
The only disadvantage I can see to properties versus methods is that while there is no problem having an interface with a get method, an interface with a set method, and an interface which combines the two (a scenario which would allow maximum flexibility with covariance and contravariance), properties do not combine nicely. I'm not sure why a read-write property isn't simply regarded the same as a read property and a write property, but it isn't. If an interface would support a read-only property and a write-only property of the same name, any attempt to access the properties through the combined interface will fail on the basis of claimed ambiguity.