Re: MVC and application state
Mark Space wrote:
Philipp wrote:
On the other hand, if for example the value is changed from somewhere
else in the code while the GUI is showing, the GUI will not be
updated. So you would have to implement some sort of ChangeListener
equivalent, is this correct?
While Eric gave great answers, I wanted point out that a ChangeListener
would only be appropriate if the value of the checkBox (or any other
intern GUI state) if the state can change while the GUI is displaying on
screen.
I would construct the GUI element (JFrame, Dialog, etc.) from the
application state (the boolean or whatever) only when I was about to use
that particular GUI element. Then I'd display it, and retrieve state
from the GUI object when the GUI is done. I'd probably call dispose()
on the element too, just to release resources, and dispose the object.
If you GUI element is persistent (i.e., it's the main application
top-window) and always displayed then yes, you'll need a ChangeListener
(or whatever interface you decide is best) to update that state so the
user can see it. But normally I associate checkBoxes with Dialog Boxes
and simple user interactions that don't need to watch for an external
state.
Mark is right, of course: It's folly to commit canaricide
by cannon. And yet, the discipline of a stern separation between
model and view can yield unexpected advantages ...
When I was teaching myself Swing, I wrote an application GUI
that took a bunch of inputs, applied some application-specific
calculations, and displayed a bunch of outputs. Pretty simple
stuff: no need for all this arms'-length separation of model and
view. But as my knowledge grew I said "Oh, Eric! You have done
Wrong! Tut-tut!" And as a sort of exercise in Rightness I went
back and rewrote the thing so all the domain-specific logic lived
in a model and all the GUI stuff lived in a view. A perfectly
pointless exercise in political purity, no?
No! Because an interesting thing happened: I decided to add
the ability to save the application data to a file and restore
it later, in another invocation -- and The Save And Restore Code
Was Just Another View! The code that managed the I/O was able
to know Nothing about the GUI, and dealt only with the model.
The GUI's code knew a very little bit about the save/restore code,
only enough to invoke it when tickled from a JMenuBar. The whole
additional capability just "fell out of" the rigid separation
between model and view. I do not think I could have managed this
anywhere near so easily with the original all-in-one design.
The lesson (for me, anyhow), is that a careful discipline can
yield unlooked-for benefits. Do not short-circuit it casually.
--
Eric Sosman
esosman@ieee-dot-org.invalid