What are all the benefits of using static variables and methods in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
There is an ongoing debate about the usage of static. When you make a variable or method static, they are not longer subject of inheritance, which makes them less flexible (e.g. problems with unit tests). That said static methods are useful if they don't need an instance. A typical example are the methods of
java.lang.Math
, and most people would agree that static is here fine. Another use is to have a factory method as a "starting point" in order to interact with with a library or framework, like getting an initial JNDI context or an EntityManager for JPA. However, factories shouldn't be overused, once you have something in your hands, you shouldn't need to call factories again. A modern replacement for factory methods is dependency injection (e.g. in Spring, Guice or EJB 3.x). Static variables are usually used for "constants" (likeMath.PI
). Enums are internally implemented using this technique. Note that the old Singleton pattern is considered now potentially dangerous (e.g. imagine that you need to introduce pooling to improve performance), and if you really want to implement a Singleton, the best way seems to be a Enum class with only one element. Other uses of static variables include things like registries or global properties, but as you can guess, this is again not very flexible and should be avoided. For performance reasons it might be fine to reuse "service objects" (I don't know of there is a well-defined name for such objects) that are expensive to create by making them static (Calendar, Random, Formatters like DateFormat, Logger), but be careful to avoid threading issues.So methods and variables should be never made static just to find a place for them. They are in conflict with OO-principles (especially with inheritance), tend to be inflexible, hard to refactor and to test. The usage of static is fine for real, immutable constants (however often Enums are the better choice for this), "service objects" or totally object-independent methods. They might be a solution when factories are needed (however, consider dependency injection or Service Provider Interfaces instead). Try to avoid other usages.
Benefits of static variables:
Benefits of static methods: