Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating without assigning to a variable

I'm inheriting the code someone else wrote at work and found that there are a lot of "new" instantiating without actually assigning to a variable:

new MyCoolClass().MyCoolMethod();

I'm just wondering if anyone has any experience with this and if this is anti-pattern or not.

like image 930
user3117252 Avatar asked Jan 15 '15 22:01

user3117252


People also ask

What does it mean to instantiate a variable?

Instantiation refers to the allocation of memory to create an instance of a class whereas initialization refers to naming that instance by assigning the variable name to that instance.

Can we create object without reference?

Simply declaring a reference variable does not create an object. For that, you need to use the new operator , as described in the next section. You must assign an object to originOne before you use it in your code.

Is instantiation the same as initialization?

Initialization-Assigning a value to a variable i.e a=0,setting the initial values. Instantiation- Creating the object i.e when u r referencing a variable to an object with new operator.

Can object class be instantiated directly?

You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)


2 Answers

Well, if you call it often like this, the method should probably be a static method, since it seems the instance isn't used or at least relevant. If you create an instance, you should use it.

I would try to write this kind of code out. For performance and understanding.

like image 120
Patrick Hofman Avatar answered Oct 13 '22 00:10

Patrick Hofman


Depending on what the MyCoolMethod() does. If it returns void, then there's no point in assigning it to a variable. I don't know about others, but I use this quite often. Whether or not it's a good practice is up for debate :)

Edit: I agree with @Patrick Hofman. My answer is actually off. I thought OP was asking why we don't have a variable to store what MyCoolMethod() returns. Please see @Patrick's answer :)

like image 27
JustAPup Avatar answered Oct 12 '22 23:10

JustAPup