【zz】Easy way to understand open/closed principle :O of S.O.L.I.D

Introduction 

This is just an attempt to make the audience understand the open/closed principle going through step by step refactoring to ultimately coming up with best design adhering OCP.

Open/Closed principle (OCP) states "Software entities should be open for extension and closed for modification".

Background

We were working on a project where we were using Oracle as the prime repository until one fine day our technical lead came up and announced that our application should support SQL Server as another data source.

Now our Data access layer had a DBConnection class with a connect method strongly bound to accept Oracle provider and establish a connection.

I ignored the detailed implementation and tried to keep things simple.

Initial Code
 

As we were in a hurry for the delivery, we could only come up with this design for the existingdbConnection class so that it now supports SQL provider too.

After Refactoring 

 

OMG ! We designed something wrong ...

Here if you can see from the above code, we are modifying the class DBConnection rather than extending it by including if else statements, this simply is against OCP.

Reason is simple if tomorrow another provider is introduced, again we have to make changes to the DBconnection class.

Ultimate refactoring ... 
 

Finally the main method ....
 

Conclusion 

The above design we could come up seems to adhere to OCP.
Now tomorrow if we have to support another Data source, we can easily do it by simply extending IDBConnection needless to make any changes to DBConnection.

So the entities are now open for extension and closed for modification.

Happy Coding. Big Grin

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值