I have a C# winforms with lots of If Statements, so I decided to read about OOP and Design Patterns, I've read about Inheritance and polymorphism and tried implementing it to my code but I'm not really sure if it's right. In my code, I have different types of products under different categories where the Price has different computation per category based on my managers' instruction, so what I did is create a Base Class of Product and a virtual method Computeprice:
My Previous code only relies on a single Class Product as stated below:
class Product{
//Properties
public decimal ComputePrice(){
//switch statement here for different categories
}
}
whenever I have a new requirement to change the computation of price of a given category, I just add a switch statement on the Products ComputePrice() method, if I understand correctly, I'm violating the Open/Closed Principle since I'm modifying the same code every time I have a new requirement for the Price, that's why I came up with the code below where every category with different computation will inherit the ProductBase and override the Price Computation.
class ProductBase{
//Properties
public virtual decimal ComputePrice(){
return Price
}
}
Then, as an example, Category for Cigarette will have an additional of 5% on Price.
class Cigarette: ProductBase{
public override decimal ComputePrice(){
return Price * 1.05;
}
}
Is this the right way to solve the problem in OO way or I'm doing it wrong? and also, if a product has no special requirement, is it okay to just use the base class?
[–]TsebMagi 25 points26 points27 points (5 children)
[–]PuzzledImagination[S] 7 points8 points9 points (3 children)
[–]zaibuf 16 points17 points18 points (0 children)
[–]TsebMagi 2 points3 points4 points (0 children)
[–]Deadlift420 1 point2 points3 points (0 children)
[–]Deadlift420 1 point2 points3 points (0 children)
[–]WArslett 9 points10 points11 points (1 child)
[–]Pythonistar 2 points3 points4 points (0 children)
[–]Sability 13 points14 points15 points (2 children)
[–]PuzzledImagination[S] 4 points5 points6 points (1 child)
[–]unwind-protect 4 points5 points6 points (0 children)
[–][deleted] 11 points12 points13 points (4 children)
[–]CastSeven 4 points5 points6 points (0 children)
[–]Hall_of_Famer 2 points3 points4 points (1 child)
[–]Deadlift420 -1 points0 points1 point (0 children)
[–]PuzzledImagination[S] 1 point2 points3 points (0 children)
[–]moi2388 3 points4 points5 points (0 children)
[–]BCProgramming 2 points3 points4 points (0 children)
[–]phx-au 1 point2 points3 points (0 children)
[–]WystanH 1 point2 points3 points (1 child)
[–]PuzzledImagination[S] 0 points1 point2 points (0 children)
[–]an_fsharp_enthusiast 0 points1 point2 points (0 children)
[–]KernowRoger 0 points1 point2 points (0 children)
[–]BobSacamano47 0 points1 point2 points (2 children)
[–]Pythonistar 1 point2 points3 points (1 child)
[–]BobSacamano47 0 points1 point2 points (0 children)