Search code examples
oopdesign-patternslanguage-agnosticbackwards-compatibilityooad

preserve backward compatibility without a separate class


Let's say there is a class called Animal which receives a request including animal's properties (type, color, size) and then it serializes and stores that in database. Over time, animal's properties change. Something is added and now we have location in addition.

There will be a version flag that can be used to branch out requests at any time.

How would you tweak animal class that it can handle the old requests as well as new ones? Is there any design patter for this?


Solution

  • I don't think you need a specific design pattern to achieve this. Here are two approaches you can try and assess which one fits your case better:

    • Overload the current Request method with additional argument location like Animal::Request(type,color,size,location) so your class can handle both. More on overloading here.
    • Add a default location argument to your existing Request method and have it treat old type,color,size calls as type,color,size,'' calls, for example. More on default arguments here.