Interfaces in Object-Oriented Design

Program to an interface, not an implementation.
— Erich Gamma

What's an interface anyway?

In object-oriented programming, an interface allows you to specify a set of function signatures and hide the implementation of those functions in an "implementing" class.   Interfaces form a contract between the class and the outside world. 

If a class implements an interface, then all methods defined by that interface must be implemented (i.e. the guts of those functions should appear in the class).

How do I define an interface?

Interfaces are available in many languages such as PHP, Java, and C#.   I will be covering PHP syntax in this article.   Interfaces were first introduced in PHP 5.  An interface cannot contain properties, only constants and methods.  All methods must be public and not contain any code inside.  

Let's say we are developing an application that processes records in flat files.   We can define an interface called File containing different functions:

interface File
{ 
    public function getRecords();
    public function saveRecords();
    public function removeRecords();
}

Assume initially that we are working with CSV files.  We define a class called CSV that implements our interface.  This class contains all the interface functions and the corresponding implementation code.

class CSV implements File
{ 
    public function getRecords()
    {
     	// logic to retrieve records from CSV file
    }
    
    public function saveRecords()
    {
    	// logic to save records to CSV file
	}
    public function removeRecords()
    {
    	// logic to remove records from CSV file
	}
}

Our application can then contain the following code:

$file = new CSV();

foreach ($file->getRecords('file.csv') as $records)
{
	// do something
}

Now say we want to extend the functionality to other file types such as XML.

We can simply define an additional class that implements the same interface:

class XML implements File
{ 
    public function getRecords()
    {
     	// logic to retrieve records from XML file
    }
    
    public function saveRecords()
    {
    	// logic to save records to XML file
	}
    
    public function removeRecords()
    {
    	// logic to remove records from XML file
	}
}

If later on, we found a more efficient way to get records from a CSV file, there would be no need to change our main application code, only the class method.

It's important to know that you cannot instantiate interfaces.  We only instantiate classes.   A class may implement multiple interfaces.