I
I
Innokenty Volnin2018-05-07 14:34:02
OOP
Innokenty Volnin, 2018-05-07 14:34:02

Are there any downsides to static methods?

Learned from a (significantly) more experienced colleague that using static methods is considered a violation of OOP principles. I would like to clarify exactly what principles we are talking about and whether they have any rational foundation under them.
Conditional situation:

public class ListToStringConverter
{
public string ListToString(List<MyObject> obj)
{
var a="";
...
...
return a;
}
}

Accordingly, I can make the method and the class itself static (and have beautiful code) or not (and create an instance of the class each time to call the method).
What will take more memory and how will the garbage collector work in general in both cases?
What will run faster?
Does the static version have any pitfalls, for example, when called from multiple threads?

Answer the question

In order to leave comments, you need to log in

10 answer(s)
D
D3lphi, 2018-05-07
@SonicAF

So, we take a thick notebook, a pen and write the phrase "Static methods are not related to OOP" until we remember it for the rest of our lives.
The essence of object -oriented programming, as the name implies, is that there must be an object . Static does not exist in the context of an object, but in the context of a class ! It follows from this that throughout the life cycle of your code there will be only one global state of the static members of the class.
You need to use statics if what you describe to it belongs to the entire group of objects, and not just one. For example, the Human class might have a static numberOfLegs() method that returns the number of legs people have. The number of legs is a common property for all people (We are talking about healthy people). In this case, it was possible to use a class constant, but this is not so important, because, in fact, a constant is also a static context. But the name is already a property of each individual person. And it is very important that static methods do not change the state of the system as a whole, do not contain side effects .
In static methods, you can take out any service logic. For example, the method for converting a number from Arabic to Roman notation should be made static.
A large number of. Moreover, not so underwater. Due to the fact that statics are global, they are difficult to test, and cannot be hacked . Global state is hard to debug. There is no way to override the implementation because objects allow it.

M
Maxim Fedorov, 2018-05-07
@qonand

Learned from a (significantly) more experienced colleague that using static methods is considered a violation of OOP principles.

Well, as it were, the basic principle of OOP is the construction of program code based on objects. What is an object? it is a certain entity that has a state and has methods that work with this state. Any static components do not belong to objects, but to a class.
In some cases, this approach is appropriate, for example, when creating helper classes. In other cases, no.
Who cares? This is saving on matches in which there is no point
It all depends on the compiler
A static method differs from a global function only in that it is bound to a class. Draw your own conclusions...

#
#, 2018-05-07
@mindtester

C# has a very elegant mechanism for extending the capabilities of existing objects, it's called extensions
https://docs.microsoft.com/ru-ru/dotnet/csharp/pro...
https://metanit.com/sharp/tutorial /3.18.php
but it is implemented only by static methods, and only in static classes the
next example is class factories , and so in C #, in the most natural way, factories are implemented precisely by static methods
, all these techniques have their place and time, you just need to figure it out
ps

Accordingly, I can make the method and the class itself static (and have beautiful code) or not (and create an instance of the class each time to call the method).
and you will have one instance of the class. this is not always appropriate. most application tasks require many instances of different classes
, however, there are situations that are solved much more elegantly, namely statics. and without it they turn out terribly clumsy
Does the static version have any pitfalls, for example, when called from multiple threads?
methods may not, depends on what they refer to? if you call other thread-safe methods (of library classes) + study and apply thread-safe algorithms - what problems can there be? (an example is LINQ extensions, which is generally built almost entirely on extensions (that is, mainly on static methods))
but remember about static fields! - even if the class is not static, it can have both static methods and fields. a static field is also a single instance for the entire program, even if the class itself is not declared static. which means that it can only be thread-safe if the static field is used readonly
conclusion - statics is a cool thing! ... but you really need to use it only when you clearly understand what you are doing? and why are you doing it this way?

E
eRKa, 2018-05-07
@kttotto

First of all, static methods and classes are not comme il faut, not because they are not OOP, but because, firstly, they give a rigid binding to the code, the code becomes inflexible, and secondly, testing code filled with statics is problematic, they give many dependencies on which cannot be abstracted. Plus global visibility.
Static methods are convenient when you use them simply as a global function that is needed in many places, for example, to convert a string or date to some kind. Only such a function should not contain business logic. In multithreaded mode, a problem can arise in the same cases as in all others - when shared data is changed inside the method.
If there is a need to make static methods with logic more serious than a list filter, for example, access to a database, then there are a couple of options in this case. First, make a singleton if you want to have one entry point for accessing the database and you want to control this point and attempts to get data from the database.
The second is dependency injection and containers for them, all kinds of IoC. In the IoC settings, you specify that to issue a single instance and it will essentially become a singlton itself, the container factory will not create a new instance for each call.
Personally, I use static methods and even fields. Having helpers is convenient, but, of course, without fanaticism.

L
Lander, 2018-05-07
@usdglander

Either a simplified constructor or small functions that do not depend on a specific object and its state are taken into static methods (For example, a method that adds two numbers passed to it will return the same result regardless of the state of the object).

M
mletov, 2018-05-07
@mletov

For example, I got burned in ASP.NET.
Different users generated reports, the report had static properties. I thought that the value of the properties for each report for each user would be different, but no. IIS, apparently, issued a report to different users from the same thread. I had to rewrite, create a report with an instance of the class and assign properties to it.
I use static methods, for example, to convert / format something into something, if the conversion algorithm is tricky enough. I put some constants or settings into static properties.

T
Therapyx, 2018-05-07
@Therapyx

judging by the comments and your "goal", I would advise using Singleton or Multiton (see Design Patterns) - one of the simplest and moreover.
a commonplace example is the implementation of a connection to a database and a certain post with a program where many instances require exactly this functionality.
Although most likely there are more elegant solutions in c# :D

D
devalone, 2018-05-07
@devalone

I would doubt the experience of a colleague. Static methods do not violate OOP principles, but should be used when an instance of the class is not needed, i.e. no need to store the state of the object, one of the common use cases is singletone, or some typical functions like sqrt, abs, etc. using class as namespace

E
Evgeny, 2018-05-08
Maltsev @loqiue

As discussed above, static methods apply to the class as a whole, not to a specific object. As for performance: if you compare a regular method inside a class and a static one, then the static one will work faster due to the fact that resources are not wasted on constructor initialization. But, you understand, usually this does not give any significant performance boost.

V
vanyamba-electronics, 2018-05-09
@vanyamba-electronics

The above example illustrates the essence of the issue rather poorly, due to the fact that it is an example of illiterate design.
You have a class - a formatted string. Let's call it FormattedString .
Next, we define operators for different types. In this case, we have a type - some kind of list of something. In OOP, there can't be a MyList class . This is GUI style design by Bill Gates, not OOP by Grady Booch and Bjorn Stroustrup.
So we have a type, let's call it ListOfFoo , which is a list of something specific, in this case a list of Foo .
And we want to add a method to convert the Foo list to a formatted string.
To do this, we add to the classFormattedString assignment operator for the ListOfFoo class :

class FormattedString
{
public:
    operator = (const ListOfFoo& src);
};

But there are situations where there is one and only one instance of an object in an application. For example, the theApp object .
How, for example, to get a link to this object. Not to transfer it on hierarchy of objects.
To do this, it is convenient to define a static method Application::getApp() , which will return a reference to the instance of the application object.
So let's formulate a rule. The program is the processor. Objects are what it creates in RAM, static objects are the registers of that processor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question