Programming to an interface, not an implementation

"Programming to an interface, not an implementation" is a software design principle that states that you should write code that depends on the abstract definition of an object's behavior, rather than its concrete implementation. In other words, your code should work with objects through their interfaces, rather than by calling their methods directly.

In object-oriented programming, interfaces are typically defined as protocols or abstract classes, which declare the methods and properties that an object must implement, but don't specify how they should be implemented. By using interfaces, you can write code that works with any object that implements the interface, without having to know the details of its implementation.

The benefits of programming to an interface, rather than an implementation, include:

  1. Loose coupling: Your code is less tightly bound to specific implementations, which makes it easier to change the implementation without affecting the rest of the code.

  2. Reusability: You can write code that works with multiple implementations of the same interface, making it more reusable and easier to maintain.

  3. Testing: You can write tests that use mock objects that implement the interface, which makes it easier to test your code in isolation.

  4. Flexibility: You can add new implementations of the interface, without affecting the code that uses it, which makes your code more flexible and adaptable to change.

By programming to an interface, rather than an implementation, you can write more flexible, reusable, and maintainable code. In Swift, you can use protocols to define interfaces, and you can use dependency injection to pass objects to your code through their interfaces, which promotes loose coupling and strong cohesion.

Next
Next

Benefits of using NSObject in Swift