Reputation: 159
Say I have a class Product {string name; double price;...}
So if I want to implement a seasonal or a discounted product, I can add declare a isPromoted/isSeasonal or I can create a new class promotedProduct : Product {...}, seasonalProduct : Product{} and much more.
I have been told that beginners tend to misuse inheritance and how it is evil. So I am not sure if I am considered misusing in this case. Or maybe they are both wrong and using interface is better etc.
Upvotes: 1
Views: 72
Reputation: 6682
One good rule of thumb is to separate what changes from what doesn't.
You cannot change type at runtime but you probably want to be able to promote/demote a product easily.
One option is to store state directly on the Product as fields (but this will get ugly if they accumulate, isLowInStock etc).
Probably better os treat Product as an entity and separate the isPromoted/isSeasonal state by:
Use #1 to guard against future change (i.e. more fields). #2 is probably overkill.
Please don't use double to represent Price - see this question or google.
Upvotes: 1
Reputation: 74277
Do seasonal or discounted products add attributes? Do they have different behavior? That's what drives inheritance. I suspect there's no real difference in behaviour and no real difference in the attributes they carry.
Hence, I'd look at a discount simply as an attribute that every product has: any product might go an sale and get discounted, so I'd have a property indicating the current discount percentage or amount (which probably defaults to zero, or perhaps it's nullable. Ditto for seasonal: should that simply be a boolean flag?
Upvotes: 0
Reputation: 182
Will products simply be on promotion or not - ie - no actual promotion details (different rates, dates etc) - if do you'll want your first solution. Otherwise you'll want a relation to a Promotions class which would store such details.
Hope this helps.
Note: this is a general programming answer having never used Java personally.
Upvotes: 1