When should we declare a method as static?

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 instance type I would have to instantiate the class just to be able to run it, which doesn't make much sense (code in portugol):

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')
Author: Maniero, 2014-04-11

3 answers

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 your example, can be run freely without the need to instantiate an object. However, due to its strong connection to the class (since it is declared in its scope) this means that its use requires to mention to its origin, and therefore the class serves as a form of Organization of functions of more general use .

Therefore, the creation of static methods (or attributes) is interesting when it is intended that they are free to use, but well identified by a context represented by the class.

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

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

The method for calculating the sine (Math.sin) is general because it calculates the value of the sine given only the angle in radians received as a parameter. So it does not require an object instance and it makes sense to be created statically. Their inclusion in the math class (Math) along with other contant methods and attributes (such as Math.PI) allows these implementations to be organized in the same meaningful (i.e., math) context for the developer who is use them.

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

  • if you just want to read the file and return the content in textual format, most likely a static method will suffice. Especially if there will be 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 that information and states.

P.S.: incidentally, I think that any existing feature in a programming language can be used incorrectly to the point of becoming a "bad practice". This is not to say that the use of the resource is always inappropriate.

 22
Author: Luiz Vieira, 2014-04-11 17:40:50

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

But is that bad?

Depends...

When is it good or bad?

  • If it's super-high-performance code that has to take advantage of each processing cycle, then this is great: less abstraction, the compiler can copy the contents of the method to the call location (inline)... everything from good to performance.

  • If your code is one that doesn't need to perform as well, you can take more advantage of abstractions, making your code more testable... all the best for system maintenance.

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

Example:

In .NET, there is the Class DateTime (it's actually a struct), which has static methods for various things.

When I want a code to be testable, rather than using, for example DateTime.Now(), I prefer to make a service called DateTimeService, which implements the interface IDateTimeService and which in its implementation calls the static methods.

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()... that is, I abstract the static class in the form of service, for 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 needed to use this method, I would use an abstraction which in turn would call the static method.

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

 10
Author: Miguel Angelo, 2014-04-11 18:09:22

Static method in object orientation

The problem with the static method is coupling, since you are using a specific class instead of injecting it as a dependency. This is why exaggeration in static code is considered a bad practice by many.

Whoever uses your class that contains the static method will be attached to it. Of course there are contexts where you will not need to change implementation, but you need to be aware in relation to static methods and their use.

 4
Author: raphael, 2019-06-22 15:40:18