I am implementing an interface that defines a method that can throw an exception if the parameters are invalid. What constitutes valid parameters depends on the implementation class. The interface also defines a method isValid()that can be used to check parameters, but returns a logical, not an exception. I found that implementing both methods will cause a lot of duplication. Consider this example:
public class Something implements SomeInterface {
public void doTheThing(SomeParameter sp) throws SpecificRuntimeException {
if(sp == null) throw new ParameterCannotBeNullException();
if(sp.getNonZeroInt() == 0) throw new ShouldBeNonZeroException();
if(!sp.someOtherCondition()) throw new SomeConditionNotMetException();
...
}
public boolean isValid(SomeParameter sp) {
if(sp == null) return false;
if(sp.getNonZeroInt() == 0) return false;
if(!sp.someOtherCondition()) return false;
...
return true;
}
}
The problem is that the checks of both methods must be consistent and essentially duplicated by logic. I tried to consolidate the checks so that both methods use the same checks, but the behavior still persists. Some things that I considered:
doTheThing() if(!isValid(sp) throw new RuntimeException();- , ,
checkParameter() isValid() do: try { checkParameter(sp); return true; } catch (SpecificRunTimeException e) { return false; }
1. , , . 2. ... -. , -, , ( , , .... , ?). , ?
?