I have three similar classes in java. They hold the data for three different forms.
The forms themselves are inner classes of these three classes extending the JPanel class. They have labels, text fields and buttons. To add these components to the JPanel, I use an
addComponent() method that sets up the GridBagConstraints for the GridBagLayout.
This method is the same for all three classes. I would like to have this method written only in one place but I can't think of an elegant way to do it.
One way I thought about was to make a formData superclass for the original classes to hold this method. If anyone has a better idea, I would appreciate it. I'm a beginner in java and I'm desperately trying to simplify my code.
I can think of two ways to accomplish this:
A utility class containing frequently used, well defined, methods.
A (possibly abstract) superclass that you inherit from.
If you do non-class-specific stuff like e.g. formatting a string, an utility class might be more preferable.
If you do stuff like class-specific instantiation/computing then you probably want a superclass. If you can think of a logical name for a superclass, like FormData in your case, then it's a good bet that a superclass is what you want.
You are right to avoid code duplication. It is almost never necessary to duplicate code, and when it becomes necessary it's probably time to look over your overall design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With