Have you ever looked under the hood of Swing? Most Swing programmers understand MVC, but I haven't talked to many who really understand how little logic really goes in a Swing component.
If you look inside JButton or AbstractButton, you find that Swing components are essentially Value Objects. The complexity of drawing a button is handled by the UI. Any model information is handled by a model (yes even for a button), and all that's left is getMargin() and setMargin().
Why is it then, that whenever someone wants to add functionality to a component, they immediately subclass it? I know the simple solution is often the best, but even on medium sized projects, this lack of flexibility quickly becomes a problem.
The largest problem with sub classing components: extendibility. Imagine creating two subclasses of JButton. Button A has feature 1. Button B has feature 2 and 3. Now you want a third button with features 1 and 3, but not feature 2.
Another major problem I find when people sublcass components is their lack of understanding of UI Delegates. Most Swing programmers know that drawing tasks are the responsibility of the UI, but few understand that most internal listeners (including many of those which communicate with the model) are the responsibility of the UI Delegate.
Many of the features added to component subclasses should be controlled by the UI. Many times the programmer will break compatibility with other look and feels because of this short-sightedness.
I believe these mistakes are often made because people are afraid of UI Delegates because of their complexity. Many behavior changes can be implemented by using a visitor pattern, or a compound UI Delegate. By applying changes to components without subclassing them, the look and feel is not broken and the logic can be separated from the component and applied based on any arbitrary set of rules.
For those who want to better understand UI delegates and the inner workings of Swing components, try reading "Hardcore JFC" by Mitch Goldstein (an unfortunate title, but a very good book).
Labels: Programming
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home