Re: Waiting for a dialog in ctor
Philipp wrote On 04/10/07 01:49,:
Hello
I have a class DataHolder which represents some data and loads it from a
file using its constructor.
The caller code would look like
DataHolder d = new DataHolder(file);
useDataHolder(d);
Now I would like the user to be able to choose some options for the file
being loaded. So inside the DataHolder ctor, I would like to show a
Dialog and _wait_ for it to return. And then get some params from that
Dialog and finish the construction of my DataHolder object.
Perhaps the constructor should also defragment all the
file systems, search the Net for applicable patches and
apply them, scan for viruses, check some interstellar noise
for signs of intelligent life, and end world hunger.
;-)
In other words, it is possible to do what you ask (see
others' responses), but I think you are trying to do too
much work inside one constructor. A constructor that tries
to be all things to all people is likely to be extremely
hard to re-use in other programs, or to work well in newer
versions of your current program as you make changes. For
example, consider an enhancement: Let the user select the
processing options beforehand (perhaps via environment
variables or Preferences or some such), so the constructor
can run unattended without the user sitting around waiting
to click a bunch of buttons. If your DataHolder constructor
insists on putting up a dialog and won't proceed until it
gets an answer, this will be a difficult enhancement ...
Suggestion: Separate the gathering of parameters from
the construction of a DataHolder, so the call now looks like
Param p = getParametersViaDialog(file);
DataHolder d = new DataHolder(file, p);
useDataHolder(d);
With this arrangement it's easy to see how you'd go
about implementing the contemplated enhancement: You'd
just write methods to build a Param object from Preferences
or environment variables or whatever, and pass the Param
to the DataHolder constructor. The constructor can then
use all the information in the Param object without needing
to know whence it came: from a dialog, from Preferences,
from a message delivered by carrier pigeon, whatever. You
might even go as far as
Param p = getParametersFromEnvironment(file);
if (p == null) {
// no default info: ask the user
p = getParametersViaDialog(file);
}
DataHolder d = new DataHolder(file, p);
useDataHolder(d);
.... and observe that the "do one thing well" DataHolder
constructor fits smoothly into this scenario, too.
Look for natural lines of cleavage in your problem
space, and exploit them in your solution.
--
Eric.Sosman@sun.com