When should we declare a method static?

Asked

Viewed 5,730 times

29

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


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

Creating this method in the type of instance I would have to instantiate the class only to be able to execute it, which doesn’t make much sense (English code):

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')
  • 3

    A good example of using método static is the standard Singleton. This pattern has a constructor privado which is instantiated by the class static method itself and ensures that one and only one instance of a given object exists in the execution of the application.

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 your example, can be run freely without the need for instantiation of an object. However, due to its strong connection to the class (since it is stated in its scope) this means that its use requires the mention is 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 of free use, but well identified by a context represented by the class.

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

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

The method for the calculation of sine (Math.sin) is general because it calculates the sine value given only the radian angle received as parameter. Therefore, it does not require an object instance and it makes sense to be created in a static way. Its inclusion in the math class (Math) together with other methods and attributes (such as Math.PI) allows organizing these implementations in the same significant context (i.e., of mathematics) for the developer who uses them.

In your example, you can consider this aspect of generality 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, very 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 can make use of previously processed states or information or can produce something that persists for future executions, it seems natural that an instance is needed to at least store this information and states.

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

10

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

But is this bad?

Depends...

When it’s good or bad?

  • If it’s high-performance code, which has to take advantage of every processing cycle, then that’s great: less abstraction, the compiler can copy the contents of the method to the call location (inline)... all good for performance.

  • If the code is one that doesn’t need to be that performance, you can take more benefit from abstractions, making the code more testable... all good for system maintenance.

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

Example:

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

When I want a code to be testable, instead of using, for example DateTime.Now(), I prefer to do a service called DateTimeService, implementing the interface IDateTimeService and that in its implementation calls the static methods.

This gives me the option to make another implementation of IDateTimeService which allows me to inject some 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.

Looking into your case:

In the case of reading files, I would make sure that there was a major implementation that is the one that actually reads a file, in a static way, and when I needed to use this method, I would use an abstraction that in turn would call the static method.

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

4

Static method in object orientation

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

Whoever uses its class containing the static method will be attached to it. Of course there are contexts where you won’t need to change implementation, but you need to be aware of static methods and their use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.