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.
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.
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.
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.
You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With