I have a dialog, which have four buttons say New, Save, Delete, Cancel. Now each of these need to perform their action. So I have defined a separate class which implements an ActionListener. I have used this class to perform each of the button action.
public class MyClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().toString() == "OK") {
// Code
} else if( .. ){
}
}
}
What I have done is, I defined an inner class which I used to do the same functionality. But what I was not getting is, is it best practice to write a separate class or is it best to use inner class. I was suggested to write in a public class so tomorrow some one can use this class to perform their action. So I have the following questions,
-
If the functionality is not called by any object (which I can’t say) then I can write it in inner class? OR
-
Is it a good practice always to write inner class which performs the actions of that dialog?
There is no general answer to these questions. If the code in
actionPerformed()is one line, writing a whole class file is usually overkill.If the code is more complex, it might be suitable to reuse but as the code grows, it also gets more specific (so you can’t reuse it anymore).
Try to follow this approach:
So in your case, you could have helper methods which do the work. Wrap them in Swing
Actions; this allows you to use them in all kinds of buttons and menus.Try to move as much work as possible into the helpers so that the actions become really simple. If in doubt, ask yourself: Is this code part of the work? Does everyone need to do this?
If yes, then the code should go into a work/helper class.
If it’s things like UI related checks (visible/enabled), conversion (string to number), validation, etc., it should go into the action.