Re: Swing application architecture question.
On Fri, 22 May 2009, Daniel Pitts wrote:
I'm starting a new project and was considering several different ways to
model and render my data.
1st way is it to use Swing models directly (TreeModel, TableModel, etc...) in
my domain. This seems like the worst way possible ;-)
The 2nd way is to implement a Swing model interface in a way that wraps my
domain model (eg, write a class MyTreeModel implements TreeModel that is a
bridge to MyTreeLikeStructure). This has the benefits of the data always
being "in sync" because the backing model is my domain model. The down side
is that the threading model for my domain must support the threading model of
Swing. This seems unsatisfactory to me.
A 3rd way would be to have a bridge between my Domain model, and a default
Swing model (eg, has a MyTreeLikeStructureListener which will update the
DefaultTreeModel instance as things change). This seems like the winner,
but I'm not sure about the development overhead in this. Does anyone have
experience with any of the three approaches?
None whatsoever, but here's my opinion:
Go the second way. Find a way to insulate the domain from Swing thread
As you say, the first way is not even worth thinking about. The third way
could be made to work, and would leave the domain clean, but maintaining
two copies of a single state is the kind of thing that always leads to
pain and bugs. Also, does you domain model have event listeners naturally?
If not, you'd have to add them to it to support the synchronising bridge,
and then you can say goodbye to purity.
Threads, on the other hand - famously easy!
So, what's the problem with the threading model? I basically know nothing
about Swing. I know that you have to do all mutation of Swing objects from
the EDT, and that you shouldn't use the EDT to do any long-running work. I
assume that the way a model works is that Swing calls in to get values,
and the model returns them, rather than that the model makes calls into
Swing - is that right? Is the problem then that your model does heavy
lifting under the hood, and you don't want to do that in the EDT? Hmm. If
that's the case, i think i might have to rescind my advice, since there's
no useful way to turn a get-a-value call into something suitably
Never attribute to malice that which can be adequately explained by
stupidity -- Hanlon's Razor