Why prefix C# interface names with an “I”

前端 未结 18 1613
清歌不尽
清歌不尽 2021-02-01 03:13

What is the rationale behind this naming convention?

I don\'t see any benefit. The extra prefix just pollutes the API.

My thinking is inline with Konrad\'s respo

18条回答
  •  太阳男子
    2021-02-01 03:59

    The need to differentiate between an interface and a class actually indicates a design flaw. In a well designed application, it will always be clear. A subclass should always be a specialization and classes can only be specialized in one subject, never more.

    A class should have a single reason for existence. It should never be required to put secondary roles in a base class. E.g.:

    public class XmlConfigurationFile : ConfigurationFile, IDisposable
    {
    }
    
    public class YamlConfigurationFile : ConfigurationFile, IDisposable
    {
    }
    

    The first one is a configuration file that is specialized in Xml, the second one is specialized in Yaml. These are also disposable, but that doesn't matter as much. You didn't create these two classes because of a different disposing processes.

    Constrast this with:

    public class XmlConfigurationFile : IDisposable, ConfigurationFile
    {
    }
    

    This will tell you that the main purpose a XmlConfigurationFile has, is that it is disposable. That you can use it as a way to represent configuration files is nice, but is secondary.

    The problem starts when you create classes that have multiple reasons for existence:

    public class MyConfigurationFile : XmlConfigurationFile, YamlConfigurationFile
    {
    }
    

    Even if XmlConfigurationFile and YamlConfigurationFile would have been interfaces, it still indicates bad design. How can your configuration file be Xml and Yaml at the same time?

    If you read through the examples given (here and elsewhere), people always struggle to find a good example of when the I-prefix matters. One of the answers here is:

    public class Dog : Pet, Mammal
    {
    }
    

    This is how this class will look like in an application about pets. A dog's main purpose is being a specialized pet, that can do pet-related things, not that it is a mammal.

    public class Dog : Mammal, Pet
    {
    }
    

    This is how the same class will look like in an application about animal classifications. It is nice to know a dog is a pet, but it's main purpose is being a specialized mammal, that can do mammal-related things.

    I think your classes should tell you the correct story about the architecture and domain of your application. Requiring an interface to be prefixed with an 'I' is a technical requirement and doesn't help you to tell your application's story better.

    Once you start writing small, dedicated, single-purpose classes, the need for knowing if it implements or extends will automatically vanish.

提交回复
热议问题