I have two separate entities:
public enum Rule implements Validatable, StringRepresentable{
//...
}
and
public inteface Filter extends Validatable, StringRepresentable{
//...
}
Where
public inteface Validatable{
public GenericValidator getValidator();
}
and
public interface StringRepresentable{
public String getStringRepresentation();
}
GenericValidator
is an abstract class having a number of subclasses I would not like users to access directly. How should I handle those things better?
I don't understand when it's better to create a class like
public class ValidatorFactory{
public Validator getRuleValidator(Rule r){ ... }
public Validator getFilterValidator(Filter f){ ... }
}
instead of implementing the Validatable
interface as I shown earlier.
Couldn't someone explain how can I make a right decision? What potentiall circumstances requires implementing FactoryMethod
a bad decision and when it would be really good?
UPD:
public interface Validator{
public ErrorCode validate();
}
public abstract class GenericValidator implements Validator{
//...
}
The ErrorCode
class encapsulates the result of the validation (null
if valiadtion's completed succsfully).
The Single Responsibility Principle
Construction of Validator is one responsibility, Filter or Rule probably carries another one. This means we should split it and usually we do so encapsulating instantiation logic in a Factory pattern.
Also note that implementing Validatable means being a ValidatorFactory. My answer would be - combine both solutions:
public class FilterImpl implements Filter {
private final Validator validator;
public FilterImpl(Validator validator) {
this.validator = validator;
}
@Override
public getValidator() {
return this.validator;
}
//...
}
public class FilterFactory {
private final ValidatorFactory validatorFactory = new ValidatorFactory();
public Filter createFilter() {
return new FilterImpl(valdatorFactory.createFilterValidator());
}
}
This is called Dependency Injection.
I use this pattern in two major cases:
A) Construction of the object isn't trivial - I don't trust the users of the API to do it correctly
B) There are more implementations and I want to choose the right one myself.
In both these cases I want to hide implementations simply because the user won't know which one to use and/or doesn't know how to construct it properly.
Always aim for simplicity and ease-of-use for your user. Ask yourself these questions:
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