Home > Software engineering >  How to model "old" and "new" list of things in Java to avoid accidental use of o
How to model "old" and "new" list of things in Java to avoid accidental use of o

Time:02-04

I've two different versions of a data structure, and there are bunch of methods that work against a list of these data structures as shown below,

class NewFooRunner {
    public double runFoos(List<Foo> foos) {
        // expecting new foos
    }
}


List<Foo> oldFoos = new ArrayList<>();
List<Foo> newFoos = new ArrayList<>();

class Foo {
    private double someNum;
}

Here NewFooRunner takes a list of Foo, and it's very easy to pass in oldFoos instead of newFoos. I wonder if there's something in the type system to avoid that. In languages with type aliasing, I could've used that. I can create a concrete class to represent OldFoos and NewFoos which holds the list internally like below.

class NewFoos {
    private List<Foo> newFoos
}

class NewFooRunner {
    public double runFoos(List<NewFoos> foos) {
        // expecting new foos
    }
}

Is that the only way to approach it?

CodePudding user response:

  • If you want OldFoo and NewFoo treated differently, then instantiate them as different classes with no common parent.
  • If you want OldFoo and NewFoo treated differently sometimes and equivalently other times, then instantiate them as different classes with a common parent.
  • If you want OldFoo and NewFoo treated equivalently, then instantiate them as the same class.

That's what the type system provides.

CodePudding user response:

If you have the luxury of changing the types in your program, that is a good approach. It does introduce a bit of clutter and a bit of inefficiency, and it introduces incompatibilities with existing code, but that tradeoff may be worthwhile.

If you can't, or don't want to, change the types in your program, then you can use pluggable types to enforce the same guarantees at compile time. There is a tutorial about how to define a type alias.

  • Related