I have a question bugging me for some days. I made a webshop for a good friend of me. The problem is I have an OOP class question.
People can buy some clothing in the shop. The problem arise how to show different information for different products?
What I have now is the following:
- abstract Product class
- Cloth extends Product
- Trousers extends Product
Problem is that trousers can contain extra information like:
- fiber type
- structure
How can I show those information in the shop? I query for all products and receive the Product class with only the selling price and name? What is the correct way to figure out it is a trouser to show those information like fiber structure on the detail page?
If you’re using jsp or jsf technologies, you don’t need to know beforehand what getters and setters a object has before you access it as a bean. However, understandably, you may want to offer alternative views for these items.
So generally speaking, my approach would be to establish an enumerator type which all Product classes must return in an abstract method. The method would be derived from all its children and give you an indicator of what type you’re dealing with and you can manage it accordingly. In otherwords, if your current object has type “Trousers”, then you include a view for that object called views/Trousers.xhtml. Alternatively, rather than return an enumerator, you could return the actual view for that object (be careful since two product types may share the same view i.e. Jeans + Trousers, so don’t use that as an indicator of type).
In the view, you know the object has already met a precondition that it is of a certain type or has explicitly indicated that particular view. At that point, you can safely call upon the properties of that object that you know it’ll have.
I hope that answers your question.
Edit:
That may not scale well depending on the number of products and how often you have to change these products. In that case, I recommend you return a string indicator instead. With that string, you can establish some patterns such as using a view with the same string indicator, etc. You could conceivably use the class name as an indicator of type, if otherwise not overridden in your derived classes.
2