> I'm reading the source code from the book "Building Parsers with Java"
> by Steve Metsker - http://www.oozinoz.com/bpwj.htm
[quoted text clipped - 3 lines]
>
> How might he have abstracted this?
The problem with trying to abstract this away is that you still have
to specify a list of instructions to use to generate an initial value in
the case where the variable is null, so you're not saving much:
(Off the top of my head, might not compile):
<pseudoCode>
interface DefaultValueGetter<T> {
T getDefaultValue();
}
class NullCheckerUtility {
public static <T> T initializeMaybe(T curValue, DefaultValueGetter<T>
initializer) {
if (curValue != null) {
return curValue;
} else {
return initializer.getDefaultValue();
}
}
}
public class ArithmeticParser {
protected Sequence expression;
protected Alternation factor;
public Parser expression() {
expression = NullCheckerUtility.initializeMaybe(expression, new
DefaultValueGetter<Sequence>() {
@Override
public Sequence getDefaultValue() {
// expression = term (plusTerm | minusTerm)*;
returnValue = new Sequence("expression");
returnValue.add(term());
Alternation a = new Alternation();
a.add(plusTerm());
a.add(minusTerm());
returnValue.add(new Repetition(a));
return returnValue;
}
});
return expression;
}
}
</pseudoCode>
The "null check" is a common enough pattern that most experienced
developers will know what you're trying to do when they see that code,
whereas this NullCheckerUtility class I mentioned above will probably
force them to start reading the implementation of this "abstraction" to
understand exactly what's going on.
- Oliver