In the previous post Object Oriented Design Principles (OODP): Open-Closed Principle(OCP) of the series OODP, we have seen how we can achieve the OCP using Shape object like Square, Circle. In this blog post, we will see how we can use the Open-Closed Principle in business scenario.
As noted in the previous post thumb rule for OCP is: We can add new features in the module without changing the existing code (CLOSED) but by adding new code (OPEN).
There is a need for a data upload program to create a sales order. Flat file would be the source of the data for this program. We are getting some fields in the flat file like Customer number, Material number, Plant etc. Obviously, it is required to validate the input before calling the BAPI to create the sales order. For this example, we would concentrate on the validation part. We will use the polymorphism to achieve the OCP for this requirement.
UML diagram would look like this:
To realize this requirement, we would create an interface LIF_SUBOBJ for common methods which we can use in different classes like Customer LCL_KUNNR, Material LCL_MATNR, etc. Definition of the interface and interface impelementing classes:
Method IS_VALID in the customer class LCL_KUNNR validates the customer number against the customer master KNA1. Method IS_VALID in the material class LCL_MATNR validates the material number against the material master MARA.
Implementation for these classes LCL_KUNNR, LCL_MATNR:
Public attribute LT_OBJ of class LCL_SO is an internal table which holds the reference of different objects like Customer LCL_KUNNR, Material Number LCL_MATNR etc. Method VALIDATE_KEYS of the class LCL_SO calls the method IS_VALID of each object reference of the table LT_OBJ attribute. We will use down cast from the object reference in LT_OBJ to object reference of LIF_SUBOBJ. Definition and Implementation of the sales order class LCL_SO is:
Full code sinppet of the program could be found here. For completion purpose, I have included local class based exception in this coding.
Change in Requirement:
After successful validation of the object, it required to set some attributes of the each object. E.g. set the customer name attribute of the object customer. We will achieve this added requirement without any modification of the method VALIDATE_KEYS.
By adding a new method SET_ATTRIBUTES in the interface LIF_SUBOBJ, it will be available in all implementing classes like LCL_KUNNR, LCL_MATNR. Call this method inside the LOOP of objects after key validation in the method VALIDATE_KEYS. Updated UML will look like this:
And updated code snippet can be found here.
Method VALIDATE_KEYS is closed for any modification:
* Achieve the same functionality (e.g. validating the object key) by creating a new class implementing LIF_SUBOBJ (e.g. LCL_WERKS for Plant validation)
* Add a new common functionality (e.g. saving data into Ztable) by creating a new method in the interface (e.g. method SAVE_DATA_TO_ZTAB in class LIF_SUBOBJ)