public Token match(ITokenType expectedToken, int tokenNum) {
if(hasToken(_currentTokenNum))
if(expectedToken == getToken(tokenNum).get_type())
return getToken(tokenNum);
return null;
}
public Token match(Class<?> clazz, int tokenNum) {
if(hasToken(_currentTokenNum))
if(clazz.isInstance(getToken(tokenNum).get_type()))
return getToken(tokenNum);
return null;
}
I tried to make a single match method, and put the condition into two methods, but it didn’t work out.
You could remove the duplication like this:
public Token match(ITokenType expectedToken, int tokenNum) {
return match(t -> expectedToken == t.get_type(), tokenNum)
}
public Token match(Class<?> clazz, int tokenNum) {
return match(t -> clazz.isInstance(t.get_type()), tokenNum);
}
public Token match(Predicate<Token> predicate, int tokenNum) {
if(hasToken(_currentTokenNum)) {
Token t = getToken(tokenNum);
if (predicate.test(t))
return t;
}
return null;
}
The condition which needs to be tested is passed in as a Predicate
(as it can't be evaluated until we've checked hasToken
).
Whether the loss of readability is worth the reduction in duplication is uncertain.
If we had many places, or widely separated places, where we were duplicating this code (rather than two, in the same class), then we are likely to change one place and not the other when requirements change.
If the implementation of match
was more complicated, then we are likely to get some of the changes wrong, even if we find all the places.
In this case it probably isn't worth removing the duplication.