Missing Opportunities for Polymorphism

本文通过一个购物车案例展示了多态在面向对象编程中的重要性。作者Kirk Pepperdine解释了如何利用多态减少冗长的条件判断语句,提高代码的可读性和维护性,并介绍了Command和Double Dispatch两种模式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值