“Program to an interface” Explained Simply

“Programming to an interface” is likely one of the most followed principles in software. Why? Because we use interfaces everywhere in software without really thinking about it.

In fact, you can technically program to an interface using an abstract class. Programming to an interface simply means programming to a supertype (ie “polymorphism”), so that the class declaring doesn’t know about the actual object types.

Imagine an abstract class Network, with two concrete implementations TCP and UDP:

Network n = new Network();
n.start()

But programming to a supertype would be:

Network network = new TCP();
network.start();

This may seem simple, but polymorphism can give us super powers by allowing us to create objects dynamically at runtime. For example:

Say we want to create methods that can change depending on what we pass to them.

private NetworkModule _netWorkModule;

public void setNetworkModule(IUdpService udpService) {
     udpService = _networkModule;
}

public void setNetworkModule(ITcpService udpService) {
     tcpService = _networkModule;
}

The most important part to realize is that these can also be declared at runtime.

public class TCPService implements ITCPService {
    
}
Network network = new TCP();
network.setNetworkModule(new TCPService());

Leave a Reply

Your email address will not be published. Required fields are marked *