【收藏】 The Simplest Anti-IF Code

本文探讨了IF语句如何增加代码间的耦合性和降低可读性,并通过实例展示了如何利用面向对象的设计原则,如继承和多态,来重构代码以提高其灵活性和可维护性。

原文地址:The Simplest Anti-IF Code

The basic problem is that IFs create dependencies, coupling between modules (methods, objects, components, etc.) and increases possible paths inside our code (which reduces legibility).

An IF seems like a quick and easy way to make changes, but for the reasons listed above, IF after IF, we create software full of duplications that can’t be modified.

Here’s a simple example:

                // Bond class
                double calculateValue() {
                       if(_type == BTP)  { 

                        return calculateBTPValue();
                       } else if(_type == BOT) { 
                                 return calculateBOTValue();    
                              } else {
                                 return calculateEUBValue();
                              }
                }

Every change in bond type, for example, a new bond to evaluate, leads to a modification in our piece of code. Imagine what it would take to modify methods with built-in IFs and SWITCHes!

                 // Bond class
                double calculateValue() {
                    _bondProfile.calculate();
                }

                // AbstractBondProfile class

                abstract double calculate();

                // classe BTPBondProfile >> AbstractBondProfile
                double calculate() {
                    ...
                }
                // classe BOTBondProfile >> AbstractBondProfile
                double calculate() {
                    ...
                }

                // classe EUBondProfile >> AbstractBondProfile
                double calculate() {
                    ...
                }


What do we gain by taking out IFs?

The advantage is that tomorrow, we can fulfill the request for a new type of bond by simply creating a new class, with the single required logic to calculate the value of that new bond.

The solution isn’t always to create a new abstract class or an interface. But the solution will always make the software flexible, communicative, testable, ready for change.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值