Re: memoized instance pattern?
"metaperl" <metaperl@gmail.com> wrote in message
news:1185095009.533190.152710@o61g2000hsh.googlegroups.com...
I'm reading the source code from the book "Building Parsers with Java"
by Steve Metsker - http://www.oozinoz.com/bpwj.htm
and in the source for ArithmeticParser.java you notice two times where
he manually checks for the existence of an object before creating it.
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