I just today learned a little about Composition over Inheritance. I was wondering if I should apply the concept to something I wrote recently.
We previously had two classes that were almost identical, aside from a couple small differences. They contained some basic database access features, but operated on different (but related) object types. So we previously had class that were structured something like this:
class BallMillDBHandler{
public BallMillDBHandler(){ ... }
public void InsertTool(BallMill tool) { ... }
public BallMill QueryTool(string toolID) { ... }
public void UpdateTool(BallMill tool) { ... }
public void DeleteTool(string toolID) { ... }
}
class DiamondToolDBHandler{
public DiamondToolDBHandler(){ ... }
public void InsertTool(DiamondTool tool) { ... }
public DiamondTool QueryTool(string toolID) { ... }
public void UpdateTool(DiamondTool tool) { ... }
public void DeleteTool(string toolID) { ... }
}
I took the majority of near-duplicated methods and refactored them out into a BaseToolDBHandler() class, and inherited it from the other two, providing a few abstract methods and properties to handle differences in accessing the database parameters themselves.
Would it make sense to make the BaseToolDBHandler a helper class instead, contained within the database accessors, and provide them a common interface the previously abstract properties/methods? Or should I leave it as a case of inheritance?
This looks like a scenario that would benefit both generics and inheritance via a base class / interface.
If you need to, you could make a base (optionally abstract) class, or an interface to use as a type constraint that would guarantee certain members that you needed the tools to have inside the method bodies.
Examples: