0

I landed in a situation where I need to derive from an existing class that represents a tcp packet, lets call it PacketA. It contains length of the packet name and name itself in it's header so there are methods in PacketA class that helps to retrieve name and name length. Now I need to create another class let's call it PacketB which has identical properties as PacketA except it has no name and name length field. So I am thinking to derive PacketB from PacketA and override methods that have different behavior. Also plan is to throw an exception from methods that PacketB don't support, mainly name and name length.

This clearly don't follow Liskov substitution principle. Is there any way to implement this in cleaner way?

  • Extract stuff common to both PacketA and PacketB to a common base class? Or perhaps derive PacketA from PacketB? – n. m. could be an AI Jul 28 '22 at 18:01
  • Do you need to pass instances of `PacketB` to methods that expect `PacketA`? If _not_, then you should [prefer composition over inheritance](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance). – jaco0646 Jul 28 '22 at 20:22
  • @jaco0646 Yes I want to pass instances of PacketB to methods that expect PacketA. Basically I want to use run time polymorphism. – Anand Shah Jul 29 '22 at 06:16
  • In that case I would set a default `name` for instances of `PacketB`. It could possibly even be an empty String. – jaco0646 Jul 29 '22 at 18:12

0 Answers0