Interface naming convention [closed]

2019-01-17 09:09发布

This is a subjective thing of course, but I don't see anything positive in prefixing interface names with an 'I'. To me, Thing is practically always more readable than IThing.

My question is, why does this convention exist then? Sure, it makes it easier to tell interfaces from other types. But wouldn't that argument extend to retaining the Hungarian notation, which is now widely censured?

What's your argument for that awkward 'I'? Or, more importantly, what could be Microsoft's?

21条回答
混吃等死
2楼-- · 2019-01-17 09:46

To separate interfaces from classes.

Also (this is more of a personal observation than dictated from upon high), interfaces describe what a class does. The 'I' lends itself to this (I'm sure it is a construct in grammar which would be great to whip out right now); an interface that describes classes that validate would be "IValidate". One that describes matching behavior would be "IMatch".

查看更多
我只想做你的唯一
3楼-- · 2019-01-17 09:50

Well, one obvious consideration would be the (very common) IFoo and Foo pair (when abstracting Foo), but more generally it is often fundamental to know whether something is an interface vs class. Yes it is partly redundant, but IMO is is different from things like sCustomerName - here, the name itself (customerName) should be enough to understand the variable.

But with CustomerRepository - it that a class, or the abstract interface?

Also: expectation; the fact is, right or wrong, that is what people expect. That is almost reason enough.

查看更多
别忘想泡老子
4楼-- · 2019-01-17 09:52

There is nothing wrong with NOT using I convention for interfaces - just be consistent and make sure it works not just for you but for whole team (if there is one).

查看更多
smile是对你的礼貌
5楼-- · 2019-01-17 09:52

It's just a convention that's intent is to prevent name collisions. C# does not allow me to have a class and an interface named Client, even if the file names are Client and IClient, respectively. I'm comfortable using the convention; if I had to offer a different convention I'd suggest using "Contract" as a suffix, e.g. ClientContract.

查看更多
Anthone
6楼-- · 2019-01-17 09:55

The fact of the matter is that everyone understands it and part of writing better code is making it easy to read and understand.

查看更多
ら.Afraid
7楼-- · 2019-01-17 09:55

Just my 2 cents:

The reason why I personally append the suffix "Interface" is because it is easier to read than the "I" prefix and because the files in the system are listed "grouped". For example:

Not so good:

Alien.php
Host.php
IAlien.php
IHost.php
IXenomorph.php
Xenomorph.php

Better:

Alien.php
AlienInterface.php
Host.php
HostInterface.php
Xenomorph.php
XenomorphInterface.php

But that's just personal taste. I think as long as one uses a consistent naming convention throughout the entire project, nothing speaks against using your own naming convention.

查看更多
登录 后发表回答