vendredi 29 octobre 2021

How to wrap a command inside if-else statements with same condition used in many places

I have a class with many public methods. Each method executes a single task when a single condition is met. The conditions in all methods are exactly the same as seen below:

public class MyClass{
    
    public ClassA method1 (arguments...){

        if(condition(aLong, aString)){
            return doSomething(arguments...)
        }else{
            throw new CustomException();
        }

    }

    public void method2 (arguments...){

        if(condition(aLong, aString)){
            doSomethingElse(arguments...)
        }else{
            throw new CustomException();
        }

    }

    public List<ClassB> method3 (arguments...){

        if(condition(aLong, aString)){
            return doSomethingDifferent(arguments...)
        }else{
            throw new CustomException();
        }
    }

    private boolean condition(Long aLong, String aString){
        // some code
        return true;
    }
}

I wanted to get rid of the repeating if...else condition by using the command pattern, so i created a class like below to wrap the actual execution inside an if else statement.

public abstract class ValidCommand<T extends Serializable> {

    private BiPredicate<Long,String> predicate;
    private Long aLong;
    private String aString
    
    public ValidCommand(BiPredicate<Long,String> predicate,Long aLong, String aString){
        this.predicate = predicate;        
        this.aLong = aLong;
        this.aString = aString;
    }

    public T execute(){
        if(predicate.test(playlistId, requestUserId)){
            return onExecution();
        }else{
            throw new CustomException();
        }
    }

    protected abstract T onExecution();

}

and I refactored the class with the methods as below:

public class MyClass{

    private BiPredicate<Long,String> predicate = (a,b) -> condition(a,b);
    
    public ClassA method1(arguments...){

        ValidCommand<ClassA> validCommand= new ValidCommand(predicate,aLong,aString){
            @Override
            protected Serializable onExecution() {
                return doSomething();
            }
        };

        return validCommand.execute();
    }
    .
    .
    .
 
}

My question is if there is a better way of doing this in Java and if is worth bothering in terms of code readability and DRY principles. Note that the number of methods inside MyClass may increase and probably all of them will share the same condition.

Aucun commentaire:

Enregistrer un commentaire