Skip to main content

Posts

Showing posts with the label static

Using static attributes in Java

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: 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 A few days back I was reviewing some code, and I realized that mutable static fields were being used in way too many places. This can make the code very brittle. 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 wi...

Do you like static imports?

Static imports have been around since Java 1.5, but they are a feature that I have rarely used, or even seen much in code. I guess that's because static imports is not a must have thing, but something that is nice to have . Using static imports takes some pain away from typing code. For example, instead of writing System.out.println("some message"); we could statically import System.out and write it as follows: static import  System.out; public class  HelloWorld  {    public static  void  main ( String args []) {      out.println ( "Hello World" ) ;    } } Well using static imports definetely takes the pain away from typing System.out every time. However sometimes using static imports can also reduce the readability of code, because we would have to look at the imports to know if a variable in code was declared within that class itself or imported statically. Hav...