[Bluej-discuss] best way to handle global data
Stephen Bloch
sbloch at adelphi.edu
Fri Dec 7 18:53:41 GMT 2007
"Aryeh M. Friedman" <aryeh.friedman at gmail.com> writes:
>Let's say I have a global piece of data (like system wide configs) and
>need to make it aviable in a number of unpredictable situations (i.e.
>the caller does not necessarly know that global data will be used)....
>for example if I am writing a replacement for JUnit and have a setting
>for say the type of test and an other for say the reporting format to
>use for results... what is the best way to handle this... I can think
>two solutions use a Singleton (i.e. a class that has a static instance
>of itself and uses that static instance for all method calls) and the
>other is to pass the global data as a param... the con of the 1st is it
>violates the spirit of the no global data precept of OO and the draw
>back of the second is the caller needs to be (unnecessarily) aware of
>the fact that a called method will need global data.
The first approach doesn't necessarily have to be global. If all the
references to the "global" data are in one class, you can put the
data in static variables of that class. If all the references to the
"global" data are in a few closely-related classes, you can put the
data in static variables of an abstract, non-public class, which you
put into a package along with all the classes that use the data.
If the data really are constant, changing only from compile to
compile rather than at run-time, you can also put them in an
interface or an abstract class and inherit from it, but that practice
is Frowned Upon in Polite Company; Joshua Bloch calls it "the
constant interface anti-pattern" and feels that an interface really
should be about the interface to a class, rather than about some
constants it needs for its implementation. A better approach is, as
I said before, to have a class that holds the values in static
variables. If you want to make sure nobody instantiates the class
(although that should be harmless), you can make it abstract and not
inherit from it.
Now that this information is in static variables of a class, you have
to ask yourself "why are they static?" A static variable is one of
which there is only one copy, not one for each class instance. So
you would then ask yourself whether it's conceivable you would ever
want two or more sets of these global data; if so, make them
NON-static variables, and have this class be basically "set of system
config data" ("set" in the non-mathematical sense).
More information about the bluej-discuss
mailing list