What does it mean to “program to an interface”?

Technology CommunityCategory: OOPWhat does it mean to “program to an interface”?
VietMX Staff asked 3 years ago

Programming to an interface has absolutely nothing to do with abstract interfaces like we see in Java or .NET. It isn’t even an OOP concept. It means just interact with an object or system’s public interface. Don’t worry or even anticipate how it does what it does internally. Don’t worry about how it is implemented. In object-oriented code, it is why we have public vs. private methods/attributes.

And with databases it means using views and stored procedures instead of direct table access.

Using interfaces is a key factor in making your code easily testable in addition to removing unnecessary couplings between your classes. By creating an interface that defines the operations on your class, you allow classes that want to use that functionality the ability to use it without depending on your implementing class directly. If later on you decide to change and use a different implementation, you need only change the part of the code where the implementation is instantiated. The rest of the code need not change because it depends on the interface, not the implementing class.

This is very useful in creating unit tests. In the class under test you have it depend on the interface and inject an instance of the interface into the class (or a factory that allows it to build instances of the interface as needed) via the constructor or a property settor. The class uses the provided (or created) interface in its methods. When you go to write your tests, you can mock or fake the interface and provide an interface that responds with data configured in your unit test. You can do this because your class under test deals only with the interface, not your concrete implementation. Any class implementing the interface, including your mock or fake class, will do.