Is it good practice to use static variables?

Is it good practice to use static variables?

Static variables are not evil – they have its adoption as global variables like constants in most cases combined with final modifier, but as it said don’t overuse them. Static methods aka utility method. It isn’t generally a bad practice to use them but major concern is that they might obstruct testing.

Why is it not a good practice to create static variables in Java?

Any code that uses static variable can be in any state. It can be within a new Object or at a class level. So the scope of static variable is open ended in a Java class. Also defining static variables is not a good practice because they go against the principles of Object Oriented Programming.

Is it bad practice to use static methods?

In short: Yes. There are many disadvantages and static methods should almost never be used. Static methods allow procedural/functional code to be shoe-horned into an Object Oriented world. Using static methods and variables breaks a lot of the power available to Object-Oriented code.

Can a class be used without a static function?

The class cannot be used on its own, without the static functions being present. This makes reusability far more difficult and isolating the class near impossible. In the example above, there is a global state. The db::$db variable can be altered from anywhere and there is no guarantee it has been set.

Why are static methods / variables used in object oriented programming?

Static methods/variables are often used because they put people from a procedural background back into their comfort zone under the guise of being “object oriented” because the functions are wrapped in a class.

What happens to the state of a static variable?

Even private static variables maintain state at a global level but simply limit its access. Any instance of the object can alter the static variable which causes ambiguity as individual instances of the object no longer have control over their own state.