static or not static
Programs-Hello!:) I had this question: when it is preferable to create static functions and when not? For example, in the case when a function uses a non-static class fields, it is better to make it static and all the necessary parameters to pass, or leave it non-static, and then nothing you tell her is not necessary, but just to access the fields of a class?
"Non-static fields of the class" -- it's kind of the instance fields of the class. If you work with them, it is better not to declare the method static. And if you need functions in the traditional sense of the word (e.g. math: sine, cosine) - then static. Because the concept of the function by itself already replaced by a static method of a class (which at first seems strange) - 10-04-2012 в 09:58:12
> what at first seems strange to think of it simply as a namespace. - 10-04-2012 в 11:24:45
Static functions should be used when you want to create an instance of the class. This, for example, a helper class. If the object is created, that is, use the new operator:
I think this example doesn't make sense to create static method.
Must read this article: Seven tips to use static fields, methods and classes
Answered: 10-04-2012 в 09:38:40
Very primitive explanation. - 10-04-2012 в 09:43:17
And if my function does not use any non-static internal fields, and all the data gets in the arguments, then mine, it would be logical to make it static. Or am I wrong? - 10-04-2012 в 10:04:54
At least the following considerations: "what for to create an unnecessary instance of the class to call this function"? - 10-04-2012 в 10:35:17
@Danil, static functions in C#, this is some analogue of pure functions, i.e. functions without side effects, which depend only on the passed parameters(with the same parameters always get odinikovo result) therefore you are right - 10-04-2012 в 10:43:16
Making functions static ability, you roll to procedural programming and not be able to apply OOP in OO language - a typical mistake of beginners. - 10-04-2012 в 11:21:30
Static functions are used for convenience, in fact they replace the design:
MyClass MyVar = new MyClass();
in some cases, shorter.
C# a garbage collector is not so important, as the design is not very bulky it turns out, but in Delphi, for example, the gain in terms of code size a lot more.
From the performance point of view static methods are also generally preferable, but not worth chasing performance at the expense of clarity and readability of the code.
Answered: 11-04-2012 в 15:10:10