Interface should not have properties?

2020-04-02 06:15发布

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 times on google, probably with wrong key words). He also told me that only methods should be in interface. Now, I am aware that is is not strict rule, since obviously in .net you can make property signature in interface and compile it.

But is this true to be a bad practice/design/oop? And why?

Pointing out to right literature or web resource would be helpful too.

Thanks

13条回答
我命由我不由天
2楼-- · 2020-04-02 06:39

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-04-02 06:39

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.

查看更多
Luminary・发光体
4楼-- · 2020-04-02 06:43

It's bad design as you pollute the implementation's variable space which is used for storing the state with variables that used as part of the class contract.

查看更多
forever°为你锁心
5楼-- · 2020-04-02 06:44

I can see no reason not to have Properties as part of your Interface. How else would you implement access to data members? Get Methods and Set Methods instead of properties. That would be just plain ugly and so 1990's.

查看更多
三岁会撩人
6楼-- · 2020-04-02 06:51

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?

查看更多
啃猪蹄的小仙女
7楼-- · 2020-04-02 06:53

The only way I can think about, why properties are bad for interfaces is, when you define interfaces for services (such as WCF, WebServices, Remoting) that are hosted on diffrent machines or application domains.

Cause properties imply that they are fast (aka. getting and setting values) which is not true for services, due to network and serialization activity. An explizit method for getting or setting values in service interfaces imply it could take some time to complete the operation.

查看更多
登录 后发表回答