Java: where should I put anonymous listener logic code?
- by tulskiy
Hi, we had a debate at work about what is the best practice for using listeners in java: whether listener logic should stay in the anonymous class, or it should be in a separate method, for example:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// code here
}
});
or
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed();
}
});
private void buttonPressed() {
// code here
}
which is the recommended way in terms of readability and maintainability? I prefer to keep the code inside the listener and only if gets too large, make it an inner class. Here I assume that the code is not duplicated anywhere else.
Thank you.