Why separation of interface and implementation?

In production code, I often see classes defined like this:

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, do we want to separate the interface and its implementation?

Or let's put it this way: why is it bad to just have one base class and let V2 extend / cancel V1 like this:

public class SomeComponent { // Some methods }
public class SomeComponentV2 extends SomeComponent 
{
  // Override methods for reimplementation
  // Add new methods for new features.
}

      

+3


source to share


2 answers


It is good practice to separate interface and class implementation, since you can easily change classes.

Imagine you want to test an application that depends on a web service that bills you for every request. Besides the class that makes real requests to this web service, you can create a class that implements the same interface but returns bogus data to avoid generating costs for each request.



Every time you inherit from a base class, chances are that you are inheriting behavior that you simply do not want to inherit. The interface is a pure contract and gives you the freedom to choose the base class regardless of the described benefit.

+1


source


The separating interface from the implementation allows full use of polymorphism. Thus, SomeComponentV2Impl will have 3 types - native, base class and interface. Here you can just use only the interface without worrying about it in subsequent classes. For example:

public void methodInOuterClass(SomeComponent smCmp){
    smCmp.runInterfaceMethods();
}

      

[Edit: This question came up in the OP's question before edites]



Why don't we use one base class for all?

Because SomeComponentV2Impl is different from SomeComponentImpl. But if they implement the same interface, you can call their implementation from the interface summarization.

0


source







All Articles