I have two classes, Foo1 and Foo2 that are not hierarchically related, so an instance of Foo1 is not an instance of Foo2 nor conversely.
In a different class from these, I have a method doStuffWithFoo that ideally should take either Foo1 or Foo2 as input, and then behave accordingly. Here’s the basic idea that I’m after:
private double[] doStuffWithFoo(Fooi foo, Bar bar1, Bar bar2, double fortyTwo) {
Fooi changingFoo = foo;
double[] fooBars = new double[N];
for (int i=0; i<N; ++i) {
double[] array = getArrayFromFoo(foo,bar1,fortyTwo);
double fooBar = getDoubleFromArray(array);
fooBars[i] = fooBar;
foo = foo.getNextFoo();
}
return fooBars;
}
where I’ve written two very different methods
private double[] getArrayFromFoo(Foo1 foo, Bar bar, double fortyTwo)
private double[] getArrayFromFoo(Foo2 foo, Bar bar, double fortyTwo)
and each Foo class implements its own getNextFoo() method that returns the same type of Foo that it takes in.
The method getArrayFromFoo doesn’t really have anything to do with the Foo classes and it takes input from the class where this method lives, so it doesn’t make sense to create a common interface for the Foos.
The ways I see to handle the situation are:
-
Make
doStuffWithFootake a generic object as input, then check whether the class isFoo1,Foo2, or something else. The problem with this approach is that I strongly prefer compile time errors to run time errors. -
Write two versions of
doStuffWithFoojust as I wrote two versions ofgetArrayFromFoo. The problem with this approach is that I’ll be duplicating a large amount of code which may cause inconsistencies when the code is changed at some point down the line.
Is there any other option? The ideal solution I have in mind is if there is a way to declare the input type to be Foo1 or Foo2, which is like approach 1 but with instant errors. Is there a way to do this in Java?
What about this: