Is it bad practice to only use static methods in a class?

12

I was studying more deeply the OOP, learning more advanced concepts like Polymorphism, Override, Classes and final methods, abstraction, namespace and etc ...

I've learned about static methods, where it can not be accessed by the object ( $this operator), and obviously can not be instantiated by the object using the -> operator, but I was looking at some projects in GitHub and vi that some of them used all static methods, everything in the class was static, from its attributes to its private methods and protected, the guy used the self:: operator to reference and use the methods of the class and its attributes, in case you wanted use the class, just use namespace of it, something like use class\ProjetoDoCara; and call the only public method that does the entire ProjetoDoCara::Operar(); service.

But then I have a question, if this is a good practice, does this not escape the rules of OOP ?

    
asked by anonymous 26.02.2016 / 20:07

6 answers

3

Good afternoon, Cassiano José!

Using lots of static variables is a bad practice, yes. Some may argue that in some specific cases it may be something usable, but in general, start by running away from the static variables.

One of the examples that you can use static variables is when it is a final variable, which will no longer have its value changed.

Consider the following case: You publish a .NET application on the web (I'll just talk about .NET, but I imagine it applies to several other platforms), and then you put a certain object as static, Product. User 1 populates this object after selecting a Product for any given operation. User 2 goes there and populates this same object to do another (or same) operation. There we have a conflict. User 1 will have a Product object with the information that User 2 has set on this object.

Recently I picked up a project that was experiencing this type of conflict, my simplest and most functional solution, I imagine, was to generate a session with information that was previously going to a static object. The Session is unique, so each user had their stored session there and can pass the information to another page of the system, for example.

So that's it, be very careful with static variables.

I hope I have helped.

Hugs.

    
26.02.2016 / 21:12
10

I decided to answer because the current answers do not talk about PHP that is the question.

First start of what I always say. This business of good or bad practice is a simplified way that people invented to give (not to use a more forceful word, but who is aware, knows what I'm talking about) rules that even they do not know well because they are talking. You have to do the right thing in every situation. So you need to understand the fundamentals and stop looking for cake recipes. This does not work well.

If it's good practice why not ask yourself if using OOP in PHP is good practice? . There I give several reasons and hope they are enough not to look like pure cake recipe.

In fact static classes do not conform much to OOP. But so what? Why do OOP? Do you have to justify yourself to adopt anything? Use to use is not a motive. If the problem does not prompt OOP to be well resolved, you do not need to follow this.

If you only have static methods, why not use common functions? Is there any reason to create a class? Always ask yourself. And remember you're using PHP, the application runs in short pieces for very little time. Overcomplicating design brings an unnecessary overhead that can make a huge difference in this execution model.

But if you do, there is nothing wrong. I just find it unnecessary. No one can cite a problem that this may cause. Of course if the problem asks for an instance, there is something else. But there you are using the wrong tool for the problem. That's something else.

Some of the problems reported in the other responses simply do not happen in PHP, or they only happen if the person does not know what they are doing. Some do not even make sense. Some answers say it is problematic, but it does not say why it is, as is typical of those who love "good practices."

Having status in a static class may be a problem, but in PHP it rarely is. As long as you do not abuse, if you know what you're doing. I'll repeat because a lot of people think PHP is .Net, C ++, Java, etc. It's not, PHP's execution is ephemeral. It is a script language and it shines through doing this. It's a shame when people try to impose models of other languages on it. And it's worth remembering that no one uses thread in PHP, even if they can. It is rare to make sense in the type of application that PHP handles. And include is your friend. Do not make him an enemy.

There are cases to do OOP, there are cases to create a class, there are cases to make everything static (even without classes), there are cases for Singleton . People need to look for things that simplify their lives, not that they complicate.

Just understand why to use a static method (it's another language, but the basis is the same) and use a static class (more general), here too . What's his job. Note that encapsulating a static method has its advantage, but may just need a normal function.

You can say, "But you did not say when to use it or not." Yes, even because you can not do that. Without a very specific case I do not know whether to use static method or not.

I did not see the project quoted in the question, but seems to be a case where static method was the best tool. If it needed to be a class, I do not know, maybe by the project type.

    
13.06.2016 / 18:10
5

Is it bad practice to only use static methods in a class?

  

No, it's not bad practice.

A completely static class can make sense even in a very well-organized code.

Completely static class escapes OOP rules?

  

Completely static class does not escape any OOP rule, just does not fit OOP.

See: OOP implies talking about objects, and a completely static class (which has only static members) will never be an object in the sense of OOP.

But nothing prevents you from using extensively the most important OOP concepts in your project, and eventually, when it makes sense, use a completely static class.

Now, if the code uses much more static classes than objects, it will hardly be framed as an object-oriented project. It will probably be more procedural. But in this case it does not mean that it has hurt rules - it just means that it is not OOP.

    
13.06.2016 / 18:39
5

I could not resist also having to post an answer.

  

Is this a good practice?

It has been said by @bigown that "good practice" or "bad practice" is sometimes simply a modinha that everyone wants to follow.

But first we should ask ourselves why use each thing.

I would not say that it is a "good practice" or "bad practice" to use a class full of static methods and properties, but would say that this is a misuse of the resource .

Most of the time, I have seen things that were done with static classes that could have been solved with the creation of various functions.

I do not usually follow something just because everyone says it's good or bad, but I like to evaluate each pattern and the need for each feature.

Let's think, is it really necessary to create a class, rather than static methods, just to make it a "function repository"?

If you want to be a bit critical (as I am), you'll notice this in the following code link.

illuminate / support / Arr

This is a class from the Illuminate\Support library, from Laravel. It is called Arr because it is a class created to do various operations with array .

If you look closely at this class, you will realize that it has each static method with the need to pass array as a parameter to work with it.

I love using the Laravel Framework, but I do not need to agree with everything that is there. Although I use this class in some parts of the systems I've developed, I realize that structuring a static whole class just to work with arrays is to misuse static methods.

If you look closely, you could do a function for each method of this class, rather than creating a class just for that.

Another thing I noticed is that no static property is used, not even to save a state. What, in my analysis, makes still more useless a use of a class with static methods to work with arrays .

What I am going to talk about next is not a standard, but only my analysis when developing classes for libraries.

Let's go to the examples

When it comes to PHP, it does not make sense to have static classes like this:

  class Util {

       public static function tratarTexto($string) {
              // faz o tratamento

             return $string;
       }
 }

Instead, something like:

 function tratar_texto($string) {
      // faz o tratamento
       return $string;
 }

But then someone will say:

  

Oh, but I wanted to separate the functions within a specific namespace, as you do with the classes. That's why I did it.

In PHP it is possible to set namespaces , not only for classes, but for functions and constants as well.

So it would be perfectly possible to organize your code in other more readable ways, such as;

namespace System\Core;

const MY_CONST_VALUE = 42;

function my_function ($str) {

}

What I realize at the end of the day is that a lot of people do things like that (not only filling a static method class, but other stuff) because they have no idea what they're doing.

So what is the static method for?

I often observe how language uses things. And the way that PHP usually uses static methods is to create the instance of the class itself, since the language does not have the ability to use multiple constructors.

An example is the class DateTime .

You can use it like this:

$date = new DateTime; // Date(object)

And if you need to initialize from other parameter passes, as in the case of a format interpretation, you can do this:

$date = DateTime::createFromFormat('d/m/Y', '20/08/2009'); // Date(object)

So, I can conclude that one of the purposes of the static method is to be able to create an alternative form of instantiation of the class itself.

Another way I see that is very common is to use factories , to facilitate the instance of a given class, given the level of complexity and dependencies of it.

Example:

// Forma complexa
new Controller(new Response(), new Request())

// Forma simplificada

Controller::factory(); // Os parâmetros Response e Request são passados internamente

Remembering that static methods do not just do what is being done above, but in my point of view, in an OOP structure it makes more sense to use a static method to aid in the inner operations of the class itself than to fill a class just to have an "organization".

The above examples are intended solely to demonstrate that what is important is the purpose of the appeal. I'm not creating any pattern to be followed blindly, but just trying to demonstrate that in some cases there are features being used that usually leave something more complicated / confusing than using others.

At the end of the day, what really matters is knowing well what the purpose of each thing is for not doing nonsense: p

    
26.10.2016 / 15:39
1

The use of static attributes and methods can not escape their definition in object orientation, otherwise a bad practice will be configured, that is, a way to facilitate a given implementation or a branch break.

In object orientation, the existence of static attributes is directed to common attributes among objects belonging to the same class in the modeling of a system, not causing a side effect on the definition of the OO system. For example, employees of the same category have, or should at least have, the same percentage increase at the end of each year, so there should be a single value for all objects.

In the same line are static methods, should act on common interests in the class. As you've mentioned that all methods were static, this is a way of making the object-oriented paradigm more like the imperative, so you lose all the myriad advantages that the development of an object-oriented system can provide.

    
27.02.2016 / 02:43
0

Looking at the OOP concepts, yes, static classes hurt the norm and it would be better to use a Singleton to create a utility class.

I'll give you an example to help you see the problem. In my c ++ code here, I found a static bRun variable in a class that I use to create all threads in my program. Instead of ending with program with exit (0) or something, I put bRun to false and all threads stop running, calling the destructors and ending the program without memory leak.

But in doing so, I'm relinquishing the advantages of Object Guidance. I can not determine the end order of threads, I can not inherit and add behavior at the end of each thread and so on.

When you look at an Open Source project, especially one in C ++, it might have used the feature of a whole static class because the variables and methods in that case load along with the program and can go to the Stack in place of go to the Heap (which is not true in many languages). Or he preferred to do without object orientation because he still did not know a good way to do it, it would take more time for him to do so.

But once you learn how to use Singleton, you'll realize that it's a design pattern that's practical enough to maintain object-orientation vantages even in those situations, and you rarely need a static method.

    
26.02.2016 / 20:48