When should we declare a method as static?

27

As a general rule it is considered bad programming practice to use static methods. But in what situations is it justified (or not justified)?

For example : If I were to create a simple method to read a text file:

Creating this method in the instance type I would have to instantiate the class just to be able to execute it, which does not make much sense (code in Portuguese):

variavel texto = novo Arquivo().lerArquivo('C:/arquivo.txt')

Already in static form I would call the method directly:

variavel texto = Arquivo.lerArquivo('C:/arquivo.txt')
    
asked by anonymous 11.04.2014 / 16:29

3 answers

22

By definition, a static attribute or method is one that does not require an instance to be used.

This means that a static method, as in its example, can be executed freely without the need to instantiate an object. However, because of its strong link to the class (since it is declared in scope), this means that its use requires the mention of its origin, and so the class serves as a form of organization of more general use functions.

Therefore, creating static methods (or attributes) is interesting when it is intended that they be freely usable, but well identified by a context represented by the class.

Classical examples are mathematical functions such as sine, cosine, square root, etc., or constants such as PI, E, etc. Many languages implement these functions statically in a class specific to mathematical elements, allowing to do, for example:

float valor = Math.sin(Math.PI);

The method for calculating sine (% cos_de%) is general because it calculates the sine value given only the angle in radians received as a parameter. Therefore, it does not require an object instance and it makes sense to be created statically. Its inclusion in the math class ( Math.sin ) along with other methods and constant attributes (such as Math ) allows to organize these implementations in a same significant context (that is, math) for the developer that uses them.

In your example, you might consider this aspect of generality of what you want to achieve with the implementation when deciding whether to create the method as static or not:

  • If you just want to read the file and return the content in the textual format, a static method will probably suffice. Especially if there are other features that will also have this character and make sense to be grouped in the same class.
  • On the other hand, if this implementation may make use of previously processed states or information, or may itself produce something that persists for future executions, it seems natural that an instance is required to at least store this information and states. / li>

Q: Incidentally, I think any feature in a programming language can be misused to become "bad practice." This does not mean that the use of the resource is always inappropriate.

    
11.04.2014 / 19:34
10

It is not the static methods that are bad practice, but the use of them. Using static methods in any code, makes this code more coupled, since static methods can not be overridden.

But is this bad?

It depends ...

When is it good or bad?

  • If it is a very high performance code, which has to take advantage of each processing cycle, then this is great: less abstraction, the compiler can copy the method content to the inline call location. .. everything good for performance.

  • If the code is one that does not need to perform that much, you can take more benefit out of abstractions, making the code more testable ... all good for system maintenance. li>

But even in the second case, static methods have their place. But I think these methods should be called, for service implementations.

Example:

In .Net, there is the class DateTime (actually it is a struct), which has static methods for various things.

When I want a code to be testable, instead of using DateTime.Now() , I'd rather do a service called DateTimeService , which implements the IDateTimeService interface and calls its static methods in its implementation.

This gives me the option to do another implementation of IDateTimeService which allows me to inject any date as if it were the value of Now() ... ie I abstract the static class in the form of service, to cases where testing is more important than performance.

Analyzing your case:

In the case of reading files, I would make a main implementation exist which is the one that actually reads a file, statically, and when I need to use this method, I would use an abstraction that would in turn call the static method.

Reason: reading files is not a task that requires very high performance, so it falls into the second case I pointed out above.

    
11.04.2014 / 20:09
3

Static method in object orientation

The problem with the static method is coupling because you are using a specific class instead of injecting it as a dependency. That's why static code is a bad practice. In object orientation this kind of method ends up limiting things.

Anyone who uses your class containing the static method will be bound to it. Of course there are contexts where you will not need to switch implementation, however you need to be aware of static methods and their use.

    
09.07.2018 / 18:41