Importance of Programming with interfaces in API/Library Development
Author: Mohammad J Iqbal
Let’s try to understand using a use case:
Use case : Suppose you work in a Product Development Company and you are requested to design a Cruise Controller class that will have adaptive speed control. Assume you have the below criteria:
a) You don’t know what type of vehicle you will need to control, it will be based on what type of customer shows interest of the cruise controller.
b) You will be provided Utility functions that can detect traffic/objects using sensors and analyze images. It tells you the estimate of the objects distance from your vehicle so that you know whether to increase/decrease speed or maintain the current speed or brake.
What are your design thoughts?
a) Since you don’t know what type of vehicles you will be provided, you can think of writing an abstract class and tell your clients to extend that class and implement their own speed functions. (Programming with abstractions)
Is it convenient to your client?
b) Better to write an interface and tell your clients that they should implement the Interface and can inject to your Cruise Controller class. (Programming with interfaces)
In that way, you can design API/Library even without knowing who will be using it.
package com.spsoft.practice.uml;
public class CruiseController {
private Drivable drivable;
private int currentSpeed;
public CruiseController(Drivable drivable){
this.drivable = drivable;
}
public void increaseSpeed(){
this.currentSpeed = this.drivable.increaseSpeed(5);
}
public void decreaseSpeed(){
this.currentSpeed = this.drivable.decreaseSpeed(3);
}
public int getCurrentSpeed(){
return this.currentSpeed;
}
}
interface Drivable{
int increaseSpeed(int speed);
int decreaseSpeed(int speed);
void brake();
}
class Train implements Drivable {
@Override
public int increaseSpeed(int speed) {
return 0;
}
@Override
public int decreaseSpeed(int speed) {
return 0;
}
@Override
public void brake() {
}
}
class CruiseControllerTest{
Drivable drivable = new Train();
CruiseController cruiseController = new CruiseController(drivable);
public void printCurrentSpeed(){
System.out.println(cruiseController.getCurrentSpeed());
}
}
Question ?
What other SOLID principal implementation you can see in my code?