1

I have the following code:

MyVersion6 myClass = returnMyClass();

// about 50 lines of code that do the following:
// do some logic with fields of myClass
// create and return another class using some fields of myClass

Now I have to support version 7 and I can return it in the returnMyClass() method.

What's the most elegant way to implement the remaining 50 lines? In this case, MyVersion6 and MyVersion7 support exactly the same methods but I don't want to do it like

if ( myClass instanceOf MyVersion6 )
      do the 50 lines using (MyVersion6) myClass 
else if ( ( myClass instanceOf MyVersion7 )
      do the exact same 50 lines using (MyVersion7) myClass 

Any ideas?

apapadak
  • 11
  • 1
  • 1
    Maybe take a look here: https://stackoverflow.com/questions/5579309/is-it-possible-to-use-the-instanceof-operator-in-a-switch-statement. You could turn the 50 lines into a method in an interface and call the method from `myClass` regardless of the class. – Josi Whitlock Jan 04 '22 at 17:32
  • A bit of elbow grease here might be more maintainable in the long run. In other words, just do the repeated lines in each factory and separate them completely. – Thorbjørn Ravn Andersen Jan 04 '22 at 19:09
  • It sounds like you would benefit from having MyVersion7 extend MyVersion6, overriding methods where necessary. Then you would only need to do those 50 lines once. – VGR Jan 04 '22 at 21:24

2 Answers2

3

I suggest you to create a interface that will be implemented by classes like MyVersion6 MyVersion7

Example

public class MyVersion7 implements someInterface{}
public class MyVersion6 implements someInterface{}

Then you can check

if ( myClass instanceOf someInterface)
      do the 50 lines using (someInterface) myClass 

instanceOf someInterface will yield true if any class has implemeneted that interface.

Dren
  • 1,239
  • 1
  • 8
  • 17
0

The new version object should avoid changing the interface (API). Since new versions share a lot of common code with the original version, I would use inheritance and let dynamic dispatch handle the difference. I would then only use casting in the case of a new version that has a specific method. But you should avoid adding specific methods to new versions.

class MyObject {
    public String toString() { return "MyObject"; }
}

class MyObjectV2 extends MyObject {
    public String toString() { return "MyObjectV2"; }
}

class MyObjectV3 extends MyObjectV2 {
    public String toString() { return "MyObjectV2"; }
    public void v3specific() { System.out.println("v3 specific method");}
}

public class JavaApplication24 {

    public static void main(String[] args) {
        MyObject[] objects = {new MyObject(), new MyObjectV2(), new MyObjectV3()};
        for (MyObject o : objects) {
            System.out.println(o);
            if (o instanceof MyObjectV3)
                ((MyObjectV3)o).v3specific();  
        }

    }

}

Cheng Thao
  • 1,467
  • 1
  • 3
  • 9