oopprinciplesopen-closed-principle

SOLID - Violated Open-Closed principle


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?


Solution

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