Call method by class or instance?

1

What would be the most correct way to call a method from another class?

It is more correct to create the object:

private MinhaClasse minhaclasse;
minhaclasse = new MinhaClasse();

Then call a method:

minhaclasse.meumetodo();

Or just call from class:

MinhaClasse.meumetodo();

Which is more advantageous? Which is less costly and less difficult for the system to perform?

    
asked by anonymous 31.03.2018 / 00:39

2 answers

4
private MinhaClasse minhaclasse;
minhaclasse = new MinhaClasse();

This code does not make sense, if it is inside a method the first line does not compile, if it is outside a method the second line does not compile.

I imagine you're talking about a static method, because if it's an instance the first option is your only option.

For a static method it does not matter, they both work the same.

However, it is considered a little confusing to call a static method as if it were an instance, so the second option would be more suitable to give more readability and prevent some error from trying to access a null instance in something that should always work . So it is not recommended.

Imagine you call a method by the instance that does something that you assume will happen to the instance, but because it is a static method it occurs globally. It will take time to realize why it does not do what you expect.

C # opted to neither allow the first option to avoid confusion.

If your concern is whether you should create the method as static or not, I am of those who think that you should always create a static method until you need to be instance, and often it is. The most common is that members of a class need to be bound to the instance.

And my choice for the method is not performance, it's even faster, it's to avoid exposing something that is not necessary. If you do not depend on anything that is in the instance why do that method be instance? Of course, it is necessary to ask why this has no relation to the instance. It may have been a wrong decision.

    
31.03.2018 / 01:25
2

The correct form depends on which method you are calling:

  • If the method has the static f modifier, use the class name.

  • If the method does not has the static modifier, use the variable with the object reference.

There is no significant difference in performance or difficulty in performing. The focus here is that each of them serves a purpose and depends a lot on how you are organizing your application.

    
31.03.2018 / 01:21