As you will probably know, the 'static' keyword in Java is used to denote fields, methods, and inner classes that do not belong to any instance of a class. They belong to the class itself and can be accessed when the class is loaded. In this post we will focus on static fields and very briefly discuss pitfalls of their usage.
Static fields are used for a variety of reasons:
When an object has a mutable static field, for all practical purposes this becomes a global variable, and thus has all the pitfalls of global variables. Some object might change the value, and another object that was depending on the old value will behave inconsistently.
An overuse of static fields is a code smell. If you use FindBugs for code analysis, it will catch such instances. FindBugs has several categories of bugs for static fields:
However, there are several uses of static fields that border on making your code unstable. In future posts I will discuss various ways in which static fields are used. I will also discuss potential pitfalls of the usage and how to avoid such situations.
Static fields are used for a variety of reasons:
- To define constants
- In the Singleton design pattern
- As global stores for application wide settings
- For mapping default objects (like formats) with Strings
- Several other reasons depending on the requirements
When an object has a mutable static field, for all practical purposes this becomes a global variable, and thus has all the pitfalls of global variables. Some object might change the value, and another object that was depending on the old value will behave inconsistently.
An overuse of static fields is a code smell. If you use FindBugs for code analysis, it will catch such instances. FindBugs has several categories of bugs for static fields:
- May expose internal static state by storing a mutable object into a static field
- Field isn't final and can't be protected from malicious code
- Field isn't final but should be
However, there are several uses of static fields that border on making your code unstable. In future posts I will discuss various ways in which static fields are used. I will also discuss potential pitfalls of the usage and how to avoid such situations.
Comments