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.
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With