Abhijeet Kashnia
Abhijeet Kashnia

Reputation: 12930

How to better organize swing code for smaller classes?

Swing classes tend to grow in size, specially when building a page with a lot of functionality which invariably leads to complicated code, a maintenance nightmare.

Now, I understand that if business logic was separated out, many of those classes would shrink drastically.

What I want to know is how to componentize swing elements, so that a page could be built with simpler building blocks? Is there some sample application that you have seen that does a lot on every page and doesn't run into thousands of lines for a few classes? Any techniques that you would suggest to break up the UI code?

Upvotes: 1

Views: 305

Answers (2)

Durandal
Durandal

Reputation: 20069

You realize that you give conflicting requirements?

  • that does a lot on every page
  • and doesn't run into thousands of lines

If you have a lot of functionality, you're going to have a lot of code to perform said functionality? User interfaces are often not trivial, for good usability they need to:

  • Layout in a nice and logical way
  • Enable/Disable components according to current UI state
  • Validate user input
  • Exchange data with some model behind the scenes

This naturally requires a few lines of code per UI element, sometimes many. (Lines of code should be taken not literally here, it may also be some kind of meta-code if you use a framework that works with XML etc).

Abstractly, the only thing you can do is keep that mess logically organized. Cleanly separate the different tasks. This can be done either by abstracting the entire behavior into each UI element (that approach usually leads to a specialized subclass for each component or a composite of component and behavior), or by putting each concern into a separate class (e.g. a Panel that declares all the components, but enabling/disabling, validation and data binding are separated into different classes).

Both approaches do not really reduce the amount of code, but they limit the amount of code that goes into one class.

Finally, factor out common/similar code you find in many places (the 'remedy' approach if you already have a mesh of existing code).

Upvotes: 2

Robin
Robin

Reputation: 36621

I found the technique described in the Humble dialogbox article rather good to start with. It also facilitated testing considerably.

Upvotes: 2

Related Questions