Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new className().methodName(); VS className ref = new className();

Tags:

java

I came across a code which my colleague uses inside an eventListner, which is :

private void someActionPerformed(java.awt.event.ActionEvent evt) {                                         
    new className().methodName(); //public class and public void methodName()
}    

I was pretty sure that :

private void someActionPerformed(java.awt.event.ActionEvent evt) {                                         
    className ref = new className(); //public class and public void 
    ref.methodName();
}

is the better option than his, as the previous method instantiates a class every time it is called.
Am I wrong? Any suggestion is appreciated, Please correct me if I am wrong .

like image 938
mustangDC Avatar asked Jul 24 '15 09:07

mustangDC


1 Answers

Both do the same thing, however one of them (the first) is 1 line shorter.

Your approach is usually recommended when you need to go through more than 2-3 objects, so new Foo().getBar1().getBar2().doStuff() is usually not recommended since it can degrade into spaghetti code and hinder the understandability of the code.

like image 119
npinti Avatar answered Nov 06 '22 07:11

npinti