blogs

Design Principals – Program to interface, not an implementation

Posted 14 December 2020

Program to interface really means program to supertype

The word interface is overloaded here, There is  the concept of interface, The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn’t locked in to the code. And we could  rephrase  “program to supertype” as “the declared type variable should be a super type , usually abstract class or interface, so that the object assign to those variable can be of any concrete implementation of the supertype which mean class declaring them does not have to know about the actual object types”

<?php


class OrderPizza
{
    private $cheesePizza;

    public function __construct(CheesPizze $cheesePizza)
    {
        $this->cheesePizza = $cheesePizza;
    }
}

Declaring variable $this->cheesePizza as type cheesePizza (a concrete implementation of Pizza) forces us to code to a concrete implementation

But program to an interface  / supertype would be

class OrderPizza
{
    private $pizza;

    public function __construct(Pizza $pizza)
    {
        $this->pizza = $pizza;
    }
}

We know its a cheesePizza but we can now use the Pizza reference Polymorphically. We  don’t know WHAT the actual Pizza type is all we care about is that it knows how to respond to makePizza()

 

Program to Interface

  • Use interfaces or abstract classes when possible, rather than concrete classes
  • Allows you to better exploit polymorphism
  • Free classes from knowledge of concrete type
  • Improves extensibility and maintainability
Leave a Reply

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