Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why separation of interface and implementation?

In production code I often see classes defined as follows:

public interface SomeComponent { // Some methods }
public class SomeComponentImpl implements SomeComponent { // Some methods}

public interface SomeComponentV2 extends SomeComponent { // Some methods }
public class SomeComponentV2Impl extends SomeComponentImpl implements SomeComponent { // Some methods }

Why in this case we want to separate the interface and its implementation?

Or put it this way, why is it bad to simply have one base class, and let V2 extend/override V1 as follows:

public class SomeComponent { // Some methods }
public class SomeComponentV2 extends SomeComponent 
{
  // Override methods for reimplementation
  // Add new methods for new features.
}
like image 503
OneZero Avatar asked May 29 '15 16:05

OneZero


1 Answers

It is a good practice to separate the interface and the implementation of a class because you can easily swap out classes.

Imagine you want to test a application which depends on a web-service which bills you for every request. In addition to have a class which performs real requests to this web-service, you could build a class which implements the same interface but returns fake data to avoid generating costs for every request.

Every time you inherit from a base-class there is a chance that you inherit behaviour you simply don't want to inherit. An interface is a pure contract and gives you the freedom to let you choose a base-class independently of the described advantage.

like image 107
Stefan Wanitzek Avatar answered Oct 11 '22 19:10

Stefan Wanitzek