I want to begin by stating that for reasons beyond the scope of this question, the database cannot be modified.
That being said, the issue is that I have 2 database objects (T1, T2) with nearly identical properties and they share the same UI code and business logic. Meaning depending on the configuration options the UI is displaying T1 data or T2 data. All the logic is for managing the data is the same as well.
What I did not want was to have my application logic code littered with instanceof operators and basically manage 2 sets of identical code. So my solution was to create a sort of wrapper class (TCombo) that takes either T1 or T2 as a constructor. All the getters and setters have the design that resembles
public String getProp1() {
if(o instanceof T1) ((T1)o).getProp1();
else(o instanceof T2) ((T2)o).getProp1();
}
and basically follows that for the setters as well so when i set a value, the DB object gets set correctly. Doing this has allowed me to use 1 set of code and just manage this TCombo class throughout the code, and this has worked great. The issue is the efficiency is horrible and since my application deals with large datasets, having to create this TCombo class for every item in the dataset creates horrid loading times.
My question is: What is the best way to manage these classes so I don't have to maintain 2 sets of logic code and also have speed?
This is more or less what interfaces were designed to handle, so you set up an interface named something like T with your common getters and setters, and then have both T1 and T2 implement it. The then code that is common to both can pass around references to the interface, and call the common methods without having to use calls to instanceof. This will let you potentially implement custom code in the getters and setters of the individual instances (e.g. if you want to do validation or something in a set method of T1 but not in T2, etc)
Another option would be having a common base class that both of your DB objects extend, and this base object contains all of the common fields between them. Then you just pass around references to the base class. This has the added benefits of not having to implement the same getters and setters in the same place.
In either case, you will need to use instanceof and casting to gain access to the methods unique to T1 and T2, but you should be able to do it much less often.
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