Is there a side effect of using many static functions?

I am currently interested in a gaming platform because this platform promises faster development.

When I see the code, there is so much static code. even the controller is declared as a static function. So all code called inside a static function must be static?

My question is, is this approach right? is there any side effect of using many static functions?

+6
source share
4 answers

A few things about static methods in an object-oriented language: let me try to explain the problems if you decide to use all static methods.

Using all static functions can be undifferentiated in an object-oriented language. You cannot override static functions in a subclass. Therefore, you lose the ability to perform polymorphism at run time by overriding.

The variables you define automatically become class variables (since all of your methods are static), so essentially you don't have any state associated with the instance.

Static methods are complicated for Mock. You might need frameworks like PowerMock to mock you. Therefore, testing becomes difficult.

The design becomes a bit complicated since you cannot create immutable classes, since you really only have a class and no instance. Thus, creating classes protected by threads becomes difficult.

+7
source

This question was asked in a similar way earlier. The simple answer is: Play uses statics where appropriate.

The HTTP model is not an OO model. HTTP requests themselves do not have a status, so static methods allow you to access controllers as functional requests from client code.

Model classes, on the other hand, are pure OO and, as a result, are not static. Some of the utility methods, such as findAll or findById, are static, but again they are not statefull and are utility methods for the class. In any case, I would expect this in the standard OO model.

Therefore, I do not think that there are any risks in doing what Play expects. This may seem strange because it challenges the norm, but it does so for reasonable reasons.

+17
source

To comment on my comment.

static methods can call non-static methods if you have an instance of something.

class A { public void nonStaticMethod() { } public static void staticMethod(String text) { // calls non-static method on text text.length(); // calls non-static method on new Object new Object().hashCode(); // calls non static method on a instance of A new A().nonStaticMethod(); } } 
+1
source

Yes, there is a side effect of using too many static functions or variables. You should avoid unnecessary static ads.

Because static members always create memory space when a class is loaded in the JRE. Even if you do not create an object of the class, it will take up memory.

-3
source

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


All Articles