1

I'm a newbie in OO design and there is one of SOLID principles is LISKOV Substitution Principle.

But in my design I've a classes named StartCommunicationMessage, ContinueCommunicationMessage, EndCommunicationMessage, AbortCommunicationMessage.

StartCommunicationMessage contains: commID, qualityOfCommunication, DestAddr, origAddr EndCommunicationMessage contains: commID, qualityOfCommunication, DestAddr ContinueCommunicationMessage contains: commID, qualityOfCommunication, DestAddr, origAddr AbortCommunicationMessage contains: commID, DestAddr

So I can make make a parent for all of these message called CommunicationMessage that contains: commID, DestAddr

But qualityOfCommunication is not found in Abort, so it will be repeated as well as it getter and setter in all other classes which make a duplication.

Is there a way to reduce this duplication either by violating the above rule or anything else?

Mahmoud Emam
  • 1,499
  • 4
  • 20
  • 37
  • As is always the case with such OOP questions, it all depends on how clients will use the base class. If I have some code which has a `CommunicationMessage&`, how should it interact with that instance? Are clients aware of things like ID or quality? Should clients write and read those values directly? Good OOP design is first and foremost good interface design, and good interface design is all about "how will others use this?". – Christian Hackl Oct 03 '15 at 12:01
  • @ChristianHackl: Yes you got my point, yes clients will aware of these fields, also some of them are optional. – Mahmoud Emam Oct 03 '15 at 12:09
  • Clients should not be aware of fields but only of member functions. Fields (aka "member variables" in C++) should almost always be `private`. – Christian Hackl Oct 03 '15 at 12:10
  • @ChristianHackl: They know about fields throw getters and setters not directly – Mahmoud Emam Oct 03 '15 at 12:14
  • That is *almost* like accessing the fields directly. There is a great answer on this topic by R. Martinho Fernandes: http://stackoverflow.com/questions/1568091/why-use-getters-and-setters (see "A public field is not worse than a getter/setter pair that does nothing except returning the field and assigning to it") – Christian Hackl Oct 03 '15 at 12:19

1 Answers1

1

If your goal is only to reduce duplication, it's not hard:

Another level of inheritance:

CommunicationMessage -> AbortCommunicationMessage, CommunicationMessageWithQuality  
CommunicationMessageWithQuality -> the other three classes  

Or classes with multiple parents:

CommunicationMessage -> All 4 classes  
CommunicationMessage and Qualityclass -> Everything but AbortMessage   

If that many classes really help for some message type,
or if they make everything more complicated, is a different thing...

deviantfan
  • 11,268
  • 3
  • 32
  • 49