views:

589

answers:

4

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.

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

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

A: 

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?

daanish.rumani
Sometimes nothing. Other times you don't want your vehicle class to have to know about XML/SOAP/YAML - you want it to concentrate on modelling a vehicle, and to keep the markup representation separate.
Dan Vinton
It breaks the notion that a class should have a single responsibility.
parkr
+7  A: 

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.

Frederik Gheysels
It might be better to rename IVehicleFormatterVisitor to just IVehicleVisitor, as it is a more generic mechanism than just for formatting.
Richard
you're absolutely right.
Frederik Gheysels
An apt solution. +1
Adeel Ansari
Isnt this just robbing peter to pay paul? so now you need a method in IVehicleFormatter and all implementations for each subclass of Vehicle... so what has this achieved?
Jordie
@Jordie this may be solved using AbstractVehicleVisitor which will implement the interface IVehicleVisitor. All the methods could be implemented to throw unsupported opertion exceptions. Concrete visitors would extend the abstract class and override the needed method used in their case
Boris Pavlović
But that only solves the compiler error. It doesn't actually fix the logic, and could be considered worse since now the compiler won't tell you that you forgot to implement something.
Robin
A: 

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.

eljenso
+2  A: 

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).

Pete Kirkham
+1 This sink looks like a Builder to me.
Jordão