Member-only story

Don’t assign static references to instance method calls in Java

Patrick Brown
3 min readJan 28, 2019

--

Photo by Luca Bravo on Unsplash

Assigning a static reference to an instance method call could be perilous. Let’s take a look at an example Java class to examine why:

/**
* Foo.java
*/

public class Foo {
public static String foo = Config.getInstance().getFoo();
}

Seems pretty innocuous in itself, but ostensibly we’re just assigning static reference in Foo to a Config singleton call. For our purposes, assume Config has both setters and getters for values we want to store configurations for. In my experience, these configuration objects are a common pattern and can be handily dependency injected for ease of testing (note how we’re not doing that here).

However, this code can behave quite unexpectedly if you’re not careful. The below test suite exemplifies this:

/**
* FooTest.java
*/

import org.junit.Test;

public class FooTest {
@Test
public void TestSetFooA() {
Config.getInstance().setFooConfig("bar");
assert Foo.foo == "bar";
}

@Test
public void TestSetFooB() {
Config.getInstance().setFooConfig("fizz");
assert Foo.foo == "fizz";
}
}

Each test does performs the exact same behavior:

  1. Set the foo configuration to a string value.
  2. Tests to see if that…

--

--

Patrick Brown
Patrick Brown

Written by Patrick Brown

Software Engineer. 70% of my body is made of code.

Responses (6)