I was discussing an exercise design problem with my friend and we came up with different solution. We are learning OOPS concept, so decided to show our solution here to experts and get their opinion.
Problem: Design class for Shirts. Shirts have different features like pattern, size, color etc.
Friend's Solution:
My Solution:
There would be concrete implementations, for example, small, medium, large for Size. Red, Blue, Yellow for Color. Isn't using Interfaces for Pattern, Size, Color is an overkill? Polymorphism should be used to encapsulate behavior, but I am using it in different way.
May some expert please let us know how we should hold different features of Shirt in Object Oriented Way? How to handle new features (e.g., shades) if they come in?
Your friend's idea is simple and I like to start with simple ideas and improve them when needed. On the other hand your solution provides great flexibility and you took OOP to the maximum by using an interface type for each variable instead of native types.
Regarding the last thing you mentioned on handling new features, well in both designs you have to open the class for modification which is not a great thing as it violates the OCP principle (classes should be open extension, closed for modification).
I would solve that by letting the Shirt
class hold properties which are common to all shirts like size, color, price or whatever and store the rest of the features that can vary in a HashMap
or a PropertyList
.
This gives great flexibility as when new features come-in you just call a method like AddFeature(name, value)
that stores the feature in the HashMap
.
I wanna make one point pretty clear, don't deep dive into design and let it consume your time. Instead start with simple ideas and improve them as you go on. Great design comes from experience and careful analysis of the business domain.