I've realized that since I've been more and more strict about the SOLID principles, my code tends to consist of more pure data objects and a lot of operator classes which seems to go against oop-principles. Specifically I often end up with type dispatchers that maps a specific object type to a suitable operator class.Let me take an example:In the old world I would have a base class FinancialInstrument with a .CalculatePrice() and .CalculateRisk() method. I would derive that to OptionInstrument and EquityInstrument with specific implementations of risk and price calculations.But due to Single Responsibility (and since there are lots of different metrics to calculate, not just prices and risks), I now have a separate RiskCalculator class and a PriceCalculator class with derived specific implementations such as OptionPriceCalculator and EquityPriceCalculator etc.When I want to iterate over instruments and calculate prices, I need have some kind of type-dispatcher class or factory that maps instruments to correct price calculation class, which just feels plain wrong and not very object oriented. I've seen this kind of pattern emerge in my projects more and more.Am I doing something wrong or is there a better way to avoid these type-dispatcher factories?
How to avoid type dispatchers when working with SOLID
object oriented;solid;single responsibility
If your classes should know how to calculate a risk, a price or other metrics, depends on what these are dependent on.E.g. to calculate a price, if you only need all the properties of FinancialInstrument then it should be implemented by the class itself. If you however need some external dependencies like the tax of a specific country, then the calculation (or at least this specific part of the calculation) should be provided by another class. If you try to explain what is a simple plain financial instrument to a third person and you don't use taxes as the part of the explaination then this is a good sign that taxes should not be part of the class.You also don't need type dispatchers to do this. because the common parts should be implemented in the classes itself and the parts that are class dependent should be implemented in another class. If you use type dispatchers then chances are high that either your classes have something in common which should be modeled by an interface so that you can use 1 additional class which can handle both these classes in the same way without having to use something like instanceof or both these classes are not the same so you need 2 additional (and semantical different) classes.If you give additional semantic information about your mentioned classes then I can also give a concrete example how I would implement it. =)