Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding parallel inheritance hierarchies

I have two parallel inheritance chains:

Vehicle <- Car
        <- Truck <- etc.

VehicleXMLFormatter <- CarXMLFormatter
                    <- TruckXMLFormatter <- etc.

My experience has been that parallel inheritance hierarchies can become a maintenance headache as they grow.

i.e. NOT adding toXML(), toSoap(), toYAML() methods to my principal classes.

How do I avoid a parallel inheritance hierarchy without breaking the concept of separation of concerns?

like image 801
parkr Avatar asked Mar 30 '09 07:03

parkr


5 Answers

I am thinking of using the Visitor pattern.

public class Car : Vehicle
{
   public void Accept( IVehicleFormatter v )
   {
       v.Visit (this);
   }
}

public class Truck : Vehicle
{
   public void Accept( IVehicleFormatter v )
   {
       v.Visit (this);
   }
}

public interface IVehicleFormatter
{
   public void Visit( Car c );
   public void Visit( Truck t );
}

public class VehicleXmlFormatter : IVehicleFormatter
{
}

public class VehicleSoapFormatter : IVehicleFormatter
{
}

With this, you avoid an extra inheritance tree, and keep the formatting logic separated from your Vehicle-classes. Offcourse, when you create a new vehicle, you'll have to add another method to the Formatter interface (and implement this new method in all the implementations of the formatter interface).
But, I think that this is better then creating a new Vehicle class, and for every IVehicleFormatter you have, create a new class that can handle this new kind of vehicle.

like image 105
Frederik Gheysels Avatar answered Nov 05 '22 15:11

Frederik Gheysels


Another approach is to adopt a push model rather than a pull model. Typically you need different formatters because you're breaking encapsulation, and have something like:

class TruckXMLFormatter implements VehicleXMLFormatter {
   public void format (XMLStream xml, Vehicle vehicle) {
      Truck truck = (Truck)vehicle;

      xml.beginElement("truck", NS).
          attribute("name", truck.getName()).
          attribute("cost", truck.getCost()).
          endElement();
...

where you're pulling data from the specific type into the formatter.

Instead, create a format-agnostic data sink and invert the flow so the specific type pushes data to the sink

class Truck  implements Vehicle  {
   public DataSink inspect ( DataSink out ) {
      if ( out.begin("truck", this) ) {
          // begin returns boolean to let the sink ignore this object
          // allowing for cyclic graphs.
          out.property("name", name).
              property("cost", cost).
              end(this);
      }

      return out;
   }
...

That means you've still got the data encapsulated, and you're just feeding tagged data to the sink. An XML sink might then ignore certain parts of the data, maybe reorder some of it, and write the XML. It could even delegate to different sink strategy internally. But the sink doesn't necessarily need to care about the type of the vehicle, only how to represent the data in some format. Using interned global IDs rather than inline strings helps keep the computation cost down (only matters if you're writing ASN.1 or other tight formats).

like image 31
Pete Kirkham Avatar answered Nov 05 '22 15:11

Pete Kirkham


You could try to avoid inheritance for your formatters. Simply make a VehicleXmlFormatter that can deal with Cars, Trucks, ... Reuse should be easy to achieve by chopping up the responsibilities between methods and by figuring out a good dispatch-strategy. Avoid overloading magic; be as specific as possible in naming methods in your formatter (e.g. formatTruck(Truck ...) instead of format(Truck ...)).

Only use Visitor if you need the double dispatch: when you have objects of type Vehicle and you want to format them into XML without knowing the actual concrete type. Visitor itself doesn't solve the base problem of achieving reuse in your formatter, and may introduce extra complexity you may not need. The rules above for reuse by methods (chopping up and dispatch) would apply to your Visitor implementation as well.

like image 31
eljenso Avatar answered Nov 05 '22 16:11

eljenso


You can use Bridge_pattern

Bridge pattern decouple an abstraction from its implementation so that the two can vary independently.

enter image description here

Two orthogonal class hierarchies (The Abstraction hierarchy and Implementation hierarchy) are linked using composition (and not inheritance).This composition helps both hierarchies to vary independently.

Implementation never refers Abstraction. Abstraction contains Implementation interface as a member (through composition).

Coming back to your example:

Vehicle is Abstraction

Car and Truck are RefinedAbstraction

Formatter is Implementor

XMLFormatter, POJOFormatter are ConcreteImplementor

Pseudo code:

 Formatter formatter  = new XMLFormatter();
 Vehicle vehicle = new Car(formatter);
 vehicle.applyFormat();

 formatter  = new XMLFormatter();
 vehicle = new Truck(formatter);
 vehicle.applyFormat();

 formatter  = new POJOFormatter();
 vehicle = new Truck(formatter);
 vehicle.applyFormat();

related post:

When do you use the Bridge Pattern? How is it different from Adapter pattern?

like image 20
Ravindra babu Avatar answered Nov 05 '22 16:11

Ravindra babu


Why not make IXMLFormatter an interface with toXML(), toSoap(), to YAML() methods and make the Vehicle, Car and Truck all implement that? What is wrong with that approach?

like image 1
daanish.rumani Avatar answered Nov 05 '22 16:11

daanish.rumani