It is very common to face duplicate codes that is likely to be refactored by adding some abstraction. Let’s see what I have been advised from our senior developers regarding with the abstractions.
AS-IS Code Example
public class MyServiceA {
public void doSomething() {
validateA();
executeA();
}
}
public class MyServiceB {
public void doSomething() {
validateB();
executeB();
}
}
As seen from the above snippet, you can see there is a chance to improve the code as it shows similar format.
From here, if we add more abstraction, it would deliver a better code.
TO-BE Code Example
Step 1.
public interface MyInterface {
boolean validate();
void execute();
}
-----
public class MyServiceA implements MyInterface {
public void doSomething() {
validate();
execute();
}
@Override
public boolean validate() {
}
@Override
public void execute() {
}
}
public class MyServiceB implements MyInterface {
public void doSomething() {
validate();
execute();
}
@Override
public boolean validate() {
}
@Override
public void execute() {
}
}
Easy, right? Adding an interface provides much better uniformity and better readability. Plus, if we use abstract class from here, things will get much better.
Step 2.
public interface MyInterface {
boolean validate();
void execute();
}
public abstract class MyAbstractClass implements MyInterface {
public void doSomething() {
validate();
execute();
}
}
-----
public class MyServiceA extends MyAbstractClass implements MyInterface {
@Override
public boolean validate() {
}
@Override
public void execute() {
}
}
public class MyServiceB extends MyAbstractClass implements MyInterface {
@Override
public boolean validate() {
}
@Override
public void execute() {
}
}
Tada! Using abstract class and interface improved much better readability and provided better code base for the future use. For example, if we need to add MyServiceC in the future, the current code delivers a message that validate() and execute() is prerequisite and needs implementation.
This skill(?) is pretty common to see in the production and widely used. Let’s keep this in mind and get it reminded whenever it’s necessary.

Leave a comment