What are all of these classes starting with I?

A consultant; that I worked with at a previous client's office, once asked this question on his first day, "What are all these classes that start with I?"

He was referring to of course to the interfaces in the solution; and it was met with a series of muffled chuckles from the other developers in the team. Here was a highly paid consultant who was unaware of what an interface was.

Or, did he have a point?

The point in an interface specifies a contract implying that an implementer is capable of 'doing' something; declaring the actions that the class can do.

Then, why are so many interfaces just an exposure of the public methods and properties that the class implements? And many that are created are more akin to the header files in C++.

Many a times I have seen someone implement a class like this.

public class VendingMachine : IVendingMachine

{
    public void ReceiveCoin(ICoin coin)

{

    ......

}

public
void PayCoinChange(ICoin coin)

{

    ......

}

}

where the interface IVendingMachine is defined as

public interface IVendingMachine

{
    void ReceiveCoin(ICoin coin);

    void PayCoinChange(ICoin coin);

}

Where is the real benefit to this? Anything implementing this interface has to implement the entire functionality of the vending machine.

Interface Segregation Principle says that no client should depend upon methods it does not use. In the above given example, if we want to implement a class that received coins but knew nothing about how to pay change then we can't simply implement IVendingMachine because then we would have to implement both the members.

Instead, we should look towards splitting the interfaces in to the actions that are being performed. One idea that I like to use around this, is to make use of the fact that the interface will start with the letter I, although, I am moving away from starting with I.

Name the interface in a way that describes succinctly what the interface is doing as if it is telling you what it can do.

public interface IReceiveCoins
{
    void ReceiceCoin(ICoin coin);
}

And then

public interface IPayChange
{
    void PayCoinChange(ICoin coin);
}

public class VendingMachine : IReceiveCoins, IPayChange
{
    .....
}

We can extend this to rename ICoin to describe what it does, but then this was just an example.

This new naming convention not only makes it clearer what the implementers can do but also helps you know that the implementation can be split amongst multiple classes. The actions can be implemented by specific classes and can be reused when required without having to carry around the additional baggage that is not necessary.

So, maybe he was right to ask "What are these classes beginning with I?"

Ebook Download
View all
Learn
View all