I have a series of classes in a project which all do essentially the same thing but on different objects. Due to some of them having been coded at different times and by different people there is some inconsistency in naming. I want to update my code in a manner that will enforce some consistency not only in the current objects but new ones that are created in the future. My understanding of programming leads me to believe that I need either a base class or an interface but I can’t figure out how to get either to work. The methods I want to have are:
internal BusinessObject MethodA(EntityObject entity)
internal Void MethodB(EntityContext context, BusinessObject obj, EntityObject entity)
The issue I am having is that in each class the “BusinessObject” and “EntityObject” will be different e.g. in one it might be “CarObject and CarEntity” and in another it would be “BusObject and BusEntity”. I still want the two methods and I still want them named MethodA and MethodB I just want to swap out the actual object types in the implementation. The implementations themselves will be different because they are using different objects.
I know the object types at compile time and need to be able to access the properties of the objects so if generics are used I need to cast the generic as the correct type in the implementation. Also the implementation of MethodA requires creating a “new” BusinessObject i.e. “BusinessObject x = new BusinessObject()” if that makes any difference.
I tried using an interface with generics in the methods and also a base class with abstract methods but I haven’t been able to figure out how to get either to work.
What is the best way to handle this? Sample code would be much appreciated.
Generics are the way
So I would declare an interface (or base class if you prefer that route) along these lines:
Then when it comes to implementing you class:
etc…
You can also enforce that your classes descend from something: