Easy to understand OpenClosedPrinciple

The definition of the OpenClosedPrinciple is that your software should be open for extension but closed for modification

So what do they actually mean by that and how do you do that. If you google this there are lot of examples to find which doesn't get you anywwhere so I worked out my own example.

Case: there are customer types which gets discount based on the type.

This is a real world example. In most of the Accounting software systems the customers are diveded by type. A good customer gets more discount than a customer which rarely place an order. So if the software is creating invoices it must detect which type of customer it is and calculate with the discount for that customerType. Well that is easy, it looking a bit like this:

if(customer.CustomerType == CustomerType.Bad)
      discount = 0

So that's easy. But if the company now changed their strategy and creates a new customertype. In that case that logic has to change. That's where the OpenClosedPrinciple is about. That logic should not be changed but it should be possible to create and use a new CustomerType.

How to do that

Create a factory which creates invoices and returns a type of incoice based on the customerType

Create invoiceTypes matching the customerType ( something like CustomerType.Bad returns a InvoiceBad ).

Define the discount in the InvoiceType

Create a processor which creates invoices of all types and call the calculate method

Uehm....maybe it easier to see to code. It's on Github




Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!