Home » Java » java – Abstract class avoid creating multiple instances of object to pass different inputs-Exceptionshub

java – Abstract class avoid creating multiple instances of object to pass different inputs-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to refactor a class using abstract class and am trying to understand if my approach is correct.

For every object I receive, I’ve a base validator which does some basic checks and then have a custom validator which performs some extra validations based on type of object. I feel this is a good use of abstract classes.

public abstract class Validator {
    BaseValidator baseValidator;
    abstract void customValidation();

    void validateObject() {
        baseValidator.validate(getInputObject());
        customValidation();
    }

    abstract String getInputObject();
}

public TypeAValidator extends Validator {
    @Override
    public void customValidation() {
        //Do something with getInputObject();
    }

    @Override public String getInputObject() {
        return "someInput";
    }
}

I don’t think having every input as part of a getter seems the right approach. If I went with a non abstract class approach, I would do this :

public TypeAValidator {
    BaseValidator baseValidator;

    public void validateObject(String inputObject) {
        baseValidator.validate(inputObject);
        customValidation(inputObject);
    }
}

With this approach, all I need to do is call typeAValidator.validateObject(inputObject) without creating a new instance of TypeAValidator everytime which I will need to do with the abstract class approach. Is there something wrong with the way I’ve modelled my abstract class.

How to&Answers:

You can mix your own two solutions to make something like this

public abstract class Validator {
    BaseValidator baseValidator;

    protected abstract void customValidationOnObject(String inputObject);

    public void validateObject(String inputObject) {
        baseValidator.validate(inputObject);
        customValidationOnObject(inputObject);
    }
}

class TypeAValidator extends Validator{

    @Override
    protected void customValidationOnObject(String inputObject) {
        // custom validate the Object
    }
}

And you can call TypeAValidator.validateObject(inputObject) on a single TypeAValidator object.