2

I have the following code snippet

class Vehicle{

 public String brand;
 public double price;
 public int productionYear;

 public String toString(String formatType) {
   switch(formatType) {
     case "JSON": // JSON formatting here
        return jsonFormattedString;
        break;
     case "XML": // XML formatting here
        return xmlFormattedString;
        break;
     default: // default formatting
       return defaultFormattedString;
    }
}

I believe that the problem with this approach is the need of changing the source code if the behaviour changes (another formatting type); and maybe other SOLID violations that I missed.

How can this be better implemented?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Vlad Danila
  • 1,222
  • 3
  • 18
  • 38
  • What is the responsibility of this class? – RWRkeSBZ Sep 10 '18 at 23:23
  • the violation is strictly regarding the 'toString' method.. – Vlad Danila Sep 11 '18 at 06:05
  • The point I was trying to make is to not be bogged down by SOLID until you have a class that makes sense. This is a "dumb" class that does not have any behaviour. One could even argue why have this class at all; if you want somewhere to hold data that can then be serialised to JSON, XML, etc. build a set of classes that do the serialisation off `Map` ojbects. You can derive new classes as your requirements for serialisation change. – RWRkeSBZ Sep 11 '18 at 08:28

1 Answers1

1

What I would do is introduce another class for "Exporting" your vehicle.

Something like this.

public class VehicleExporter
{
    public string ExportAsJson(Vehicle vehicle)
    {
        // Do the JSON thing
    }

    public string ExportAsXML(Vehicle vehicle)
    {
        // Do the XML thing
    }
}

The big thing with your design is not as much breaking the open closed principle, but the responsibility of the vehicle class.

When your class is doing the toString(), it is essentially trying to do something outside of it's responsibility.

Please let me know if I can clarify further.

Marcel De Villiers
  • 1,682
  • 4
  • 15
  • 17