← All blog posts

Static class variables

August 13, 2024 · Programming

The static keyword held a very special place in my mind as programmer. The concept spans across languages, like Java, C#, Javascript and even Python (!).

The Singleton pattern

My first actual useful usage of the static class attribute in Java was when back in the day, I was implementing the Singleton design pattern. A typical implementation looks like this:

public class ClassicSingleton {
private static ClassicSingleton defaultInstance;

private ClassicSingleton() {
// do the math here
}

public static ClassicSingleton getInstance() {
if (ClassicSingleton.defaultInstance == null) {
ClassicSingleton.defaultInstance = new ClassicSingleton();
}

return ClassicSingleton.defaultInstance;
}
}

This by-the-book implementation declares a static variable on the class ClassicSingleton and initializes it, when the getInstance() method is called.

A more Java-esoteric implementation would be the following:

public class EsotericSingleton {
private static EsotericSingleton defaultInstance;

static {
defaultInstance = new EsotericSingleton();
}

private EsotericSingleton() {
// do the math here
}

public static EsotericSingleton getInstance() {
return defaultInstance;
}
}

A bit more elegant, it avoids the null check of the previous implementation, by initializing the variable through the static initializer block. This block exists in various forms in several languages also, so you can easily port this implementation to your favorite language.

Hacking the static initializer block

But there are many interesting and funny uses of the static initialization block.

Imagine this class:

public class Main {
public static void main(String[] args) {
System.out.println("Boom");
}
}

So you need the main method to run a Java program, right? No.

public class Main {
static {
System.out.println("Boom!!");
}

public static void main(String[] args) {
//do nothing
}
}

This is the empty main pattern :), and it becomes more funny …

public class Main {
static {
System.out.println("Boom!!");
}
}

… with the no main pattern, which of course throws an exception when you run it, but it still runs nevertheless.

Static initialisers in Javascript

Javascript has also static initialisers that work as follows:

class ClassWithStatics {
static foo;

static {
foo = '123';
}
}

The code is executed on import and the async keyword cannot be used, to perform async io operation.

Maybe, it can be wrapped to add async implicit properties, but it would be a bit tricky in terms of readbility.

Note: Source code can be found on github