Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it better to replace new ActionListener() with lambda? And why?

I have been using new ActionListener() when creating an action listener, but I receive a warning when using this telling me I should replace it with lambda. Nothing changes with the actual functionality when I switch between the two, but I am just curious why lambda is better.

jb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { popUp.dispose(); } });

vs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jb.addActionListener(e -> popUp.dispose());

>Solution :

Signal to noise ratio. addActionListener already tells us that it’s an action listener. The new ActionListener() part provides no information to the programmer. Likewise, every action listener has a actionPerformed, so specifying that explicitly is mostly pointless in the simple case. So since modern Java versions allow us to omit it, we should.

You would still want an anonymous class if you had some instance variables or other private methods inside the listener. Of course, in this case, you might be better suited to use a named inner class to begin with, since your needs have clearly expanded.

Basically, anonymous classes were a crux from before lambdas existed in Java. Both solve the same problem: "I’ve got a tiny piece of functionality and don’t want to give it a proper name since it’s trivial". So if you’ve got something trivial, you should use the shorter of the two. And if you’ve got something nontrivial, you should give it a name and document it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading