Design choices and patterns for passing contextual runtime information.
Hello fellow Engineers,
So, I'm working on a (hand written) English imperative statement
parser in Java, and I was thinking that eventually, I might need to
pass context to different nodes in the "parse tree". Having to parse
context information is an even more general problem than this parser,
so I was thinking about the best way(s) to approach this sub-problem.
I personally dislike the needless use of singleton, since often its
not truly required, and is often confused with the "locater" pattern.
The straight forward solution is to pass a context object to all
methods on all objects that need it. Some methods might only need it
in order to forward it to the other objects. This seems like a bit of
a waste to me, although it does keep it clear and explicit where the
context comes from.
The other alternative is to pass the context to the constructor of all
the classes involved, so that they have a reference to it at all
times. This is a slightly more useful approach, but many of my
parsing methods are "static", they return an object of the type that
matches the parsed text. Maybe that's the wrong approach (comments
welcome on *that* problem as well.
The third alternative is to use a ThreadLocal variable. This thread
local variable would be the context object. This is a little close to
a global variable, but it is thread-safe, and it seems like it would
be (if properly encapsulated) a cleaner approach.
I'm sure I'm going to get a lot of strong opinions on the right way to
do this, so I look forward to reading the reasoning behind those
x-posted to comp.lang.java.programmer, comp.software.patterns, and
follow-up to comp.lang.java.programmer.