Static classes / fields. How often do you use it?

Sometimes it is very difficult to find an error in the application due to static data. Is there a good approach to using static data in OOP, or is it better to avoid it? Thanks in advance.

UPDATE:

How often do you use static classes and for what purpose?

+4
source share
2 answers

In general, static methods lead to complex code testing, since

  • we cannot know if any other class changed the possible state,
  • we cannot easily make fun of or disable a static implementation.

However, there are several valid use cases.

I would usually refrain from using static methods and give the default principle that the existence of any static content should be motivated.

As @Louis pointed out, static variables are useful for providing unit instance constants. Typically, this can also apply to member variables storing objects such as Logger.

+2
source

Static should not be abused, but in some situations it is worth using, you should use static methods to provide factory methods or helper methods that are not directly related to the instance object.

A static approach is worth every time you want to perform an action or present data related to a class and not an instance of an object, so the approach of using a static should not be avoided at all, but only used when it is really necessary.

As in most situations, there is no absolute answer to your question (avoid or do not use static), it depends on the context, however you should not abuse static ...

+1
source

Source: https://habr.com/ru/post/1395508/


All Articles