My code is used as part of two big versions and interact with external interface. In one of the versions new API was added (I need to call a new method).
I would like to prevent maintaining two versions of my code, and use if statement:
If VersionX
Do Method1()
If VersionY
Do Method2()
assuming method2() is the new function I need to call, is there a way that the code can compile only on runtime (means that if I run on VersionX system, there would be no problem of compilation and exceptions though method 2() does not exist there)?
You can achieve this with an interface and two classes:
interface API {
void Method();
}
class APIX implements API {
void Method() {
someInstance.Method1();
}
}
class APIY implements API {
void Method() {
anotherInstance.Method2();
}
}
Then depending on the current version, you create an instance of either APIX or APIY:
API api;
if (isVersionX)
api = new APIX();
else
api = new APIY();
api.Method();
This code is compiled against the newer API wich contains both methods. Since class loading is on demand only, the class using the newer method is not loaded when only the old API is available and you don't have any conflicts at run-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With