programming

Mutable Shared State: List of Values

When we have mutable shared state, written code is harder to understand. We have to know where the state has become shared and where it is modified. Usually those location are on different places. It become worse, when inner state of a class is shared.

Example mutable shared state of a class

public class Foo {

    private List<String> list;

    public Foo() {
        this.list = new ArrayList<>();
    }

    public List<String> getList() {
        return list;
    }

    public int size() {
        return list.size();
    }
}
public class Bar {
    private List<String> list;

    public Bar(List<String> list) {
        this.list = list;
    }

    public boolean add(String s) {
        return list.add(s);
    }

    public int size() {
        return list.size();
    }
}
@Test
public void test(){
    Foo foo = new Foo();
    Bar bar = new Bar(foo.getList());
    bar.add("value 1");
    Assert.assertEquals(1, bar.size());
    Assert.assertEquals(0, foo.size());
}

Test fail, because classes Foo and Bar has the same List object. When string was added, it was added to same list.

In the following code Foo class does not expose inner state. It returns a new list.

public class Foo {

    private List<String> list;

    public Foo() {
        this.list = new ArrayList<>();
    }

    public List<String> getList() {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.addAll(list);
        return arrayList;
    }

    public int size() {
        return list.size();
    }
}

Conclusion

When you won’t find, when some value of an object was set, check if object is shared.

Leave a Reply