0

I need to respect the LSP while supporting multiple data types (templates can't be used) and I have a dilemma between inheritance and composition. If I use inheritance, the base class cannot be used by itself, it must be casted everytime. Does that violate the LSP?

Inheritance would be:

enum eDataType{
    FLOAT,
    INT,
    }

class IObject{
  eDataType dataType;
  ...
};
class IntObject : IObject{
int paramA;
int paramB;
...
};
class FloatObject : IObject{
float paramA;
float paramB;
...
};

While using composition it would look like:

struct IntObject{
int A;
int B;
}
struct FloatObject{
float A;
float B;
};
class Object{
  eDataType dataType;
  IntObject* intObject;
  FloatObject* floatObject;
  Object(eDataType dataType){
   if(dataType == FLOAT){ floatObject = new FloatObject();}
     ...
   }
  void updateData(Message* incomingMessage){
   if(dataType == FLOAT)
    ...

};
JCMS
  • 128
  • 9
  • I don't see how you can follow the LSP with either approach. – juanchopanza Jan 21 '15 at 21:51
  • 2
    what do you mean "the base class cannot be used by itself, it must be casted everytime"? also you can use template if type is the only difference – Bryan Chen Jan 21 '15 at 21:51
  • Liskov is a TLA now? – Thomas Padron-McCarthy Jan 21 '15 at 21:57
  • @Bryan Chen : Templates cannot be used due to requirements. What I mean with the base class, is that it would server as a pointer definition for container and only contain the field "dataType". Any operation would require a cast to the implementation – JCMS Jan 22 '15 at 05:02
  • @juanchopanza: Well, with the composition approach it doesn't apply. – JCMS Jan 22 '15 at 05:03
  • Neither does your inheritance with casting approach. So it isn't clear what you are asking. You have no dilemma, because you can't satisfy your requirements with either approach. You need a to try different approach, or to change the requirements. – juanchopanza Jan 22 '15 at 06:22

0 Answers0