Missing Opportunities for Polymorphism

Missing Opportunities for Polymorphism

Kirk Pepperdine

POLYMORPHiSM iS ONE OF THE GRAND iDEAS that is fundamental to OO. The word, taken from Greek, means many (poly) forms (morph). In the con- text of programming, polymorphism refers to many forms of a particular class of objects or method. But polymorphism isn’t simply about alternate implemen- tations. Used carefully, polymorphism creates tiny localized execution contexts that let us work without the need for verbose if-then-else blocks. Being in a context allows us to do the right thing directly, whereas being outside of that context forces us to reconstruct it so that we can then do the right thing. With careful use of alternate implementations, we can capture context that can help us produce less code that is more readable. This is best demonstrated with some code, such as the following (unrealistically) simple shopping cart:

    public class ShoppingCart {
        private ArrayList<Item> cart = new ArrayList<Item>();
        public void add(Item item) { cart.add(item); }
        public Item takeNext() { return cart.remove(0);  }
        public boolean isEmpty() { return cart.isEmpty(); }
}

Let’s say our webshop offers items that can be downloaded and items that need to be shipped. Let’s build another object that supports these operations:

    public class Shipping {
        public boolean ship(Item item, SurfaceAddress address) { ... }
        public boolean ship(Item item, EMailAddress address { ... }
}
When a client has completed checkout, we need to ship the goods:
while (!cart.isEmpty()) { shipping.ship(cart.takeNext(), ???);
}

??118

97 Things Every Programmer Should Know

?

???????????????The ??? parameter isn’t some new fancy elvis operator; it’s asking whether I should email or snail-mail the item. The context needed to answer this ques- tion no longer exists. We have could captured the method of shipment in a boolean or enum and then used an if-then-else to fill in the missing parameter. Another solution would be to create two classes that both extend Item. Let’s call these DownloadableItem and SurfaceItem. Now let’s write some code. I’ll pro- mote Item to be an interface that supports a single method, ship. To ship the contents of the cart, we will call item.ship(shipper). Classes DownloadableItem and SurfaceItem will both implement ship:

    public class DownloadableItem implements Item {
        public boolean ship(Shipping shipper, Customer customer) {
            shipper.ship(this, customer.getEmailAddress());
        }
    }
    public class SurfaceItem implements Item {
        public boolean ship(Shipping shipper, Customer customer) {
            shipper.ship(this, customer.getSurfaceAddress());
} }

In this example, we’ve delegated the responsibility of working with Shipping to each Item. Since each item knows how it’s best shipped, this arrangement allows us to get on with it without the need for an if-then-else. The code also demonstrates a use of two patterns that often play well together: Command and Double Dispatch. Effective use of these patterns relies on careful use of polymorphism. When that happens, there will be a reduction in the number of if-then-else blocks in our code.

While there are cases where it’s much more practical to use if-then-else instead of polymorphism, it is more often the case that a more polymorphic coding style will yield a smaller, more readable and less fragile codebase. The number of missed opportunities is a simple count of the if-then-else statements in our code.

时间: 2024-10-20 09:08:48

Missing Opportunities for Polymorphism的相关文章

ARTS Week 18

Feb 24, 2020 ~ Mar 1, 2020 Algorithm Problem 371. Sum of Two Integers(两整数之和) 题目链接 题目描述:给定两个数字,求两个数字之和.不能使用加法运算 思路为:不能使用加法运算,那么可以考虑使用位运算来实现加法.先观察只有一位数的情况: 0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 0(进位为 1) 这个特性符合异或运算,那么可以通过异或运算来实现无进位加法,那么该如何计算进位呢?我们知道,二进制

Anti-If: The missing patterns--转

原文地址:http://code.joejag.com/2016/anti-if-the-missing-patterns.html Around 10 years ago I encountered the anti-if campaign and found it to be an absurd concept. How on earth would you make a useful program without using an if statement? Preposterous.

The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeansException

"The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeansException" "构造函数ClassPathXmlApplicationContext(字符串)是指缺失类型BeansException" 出现错误的原因:jar没有正确引入,即使表面上你能import包. import org.junit.Test; import org.spring

error C2143: syntax error : missing &#39;;&#39; before &#39;{&#39;

这是我在实现哈夫曼树的时候,遇到的错误,具体为什么我也不清楚!!!因为这是我用学校实验室的电脑编译出现的错误(用的软件是VC6.0,贼老的版本!!!),我自己的是Code Blocks(没有出错)??? 代码如下: for ( i = 1; i <= n; i++ ) { huffNode HT[i](w[i],0,0,0);//初始化前n个节点(构造哈夫曼树的原始节点) } 然后,就有错了(-_-!) error C2057: expected constant expression erro

LeetCode题解-----First Missing Positive

Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] return 3,and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. 分析: 因为数组的大小为n,因此那个缺失的整数只可能的范围[1,n+1] 方法一:需要O(n)的空间,设

the tomcat installation directory is not valid. It is missing excepted file or folder

问题描述 : the tomcat installation directory is not valid 原因 : 我在上一页没有选择apache tomcat 7.0,因为eclipse版本太低,只有到6.0的server供选择 所以这边就算把Name改成7.0,还是配置不了 解决方案: 安装更高版本的eclipse the tomcat installation directory is not valid. It is missing excepted file or folder,布布

41. First Missing Positive【leetcode】寻找第一个丢失的整数,java,算法

41. First Missing Positive Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] return 3,and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. 题目:寻找第一个丢失的整数意思为[1,2,4,5,

41. First Missing Positive(C++)

Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] return 3,and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. Solution: class Solution { public: int firstMissingP

【Java】SVN下载maven项目到eclipse之后,项目红叉,pom.xml出现Missing artifact fakepath:dubbo:jar:2.8.5等缺少jar包情况

刚入公司,从svn上把代码弄下来之后导入eclipse,一般是maven项目,往往项目都会有红叉.如果排除代码本身问题,一般是jar包没有. 鼠标点开pom.xml文件,在约束那里一般有红叉,鼠标放上去一般会提示Missing artifact fakepath:dubbo:jar:2.8.5等提示,表示本地仓库缺少jar包. 如果本地仓库确实没有,一般点击maven-update project,他会自动去私服下载. 如果你本地仓库已经有了,往往是之前没有下完整的.lastUpdated的ja