3.10 witch statements(switch 惊悚现身)

来源:互联网 发布:店铺效果图制作软件 编辑:程序博客网 时间:2024/06/04 19:52

面向对象程序的一个最明显特征是:少用switch语句。

switch语句常常根据类型码进行选择,所以应该使用extract method将switch语句提炼到一个独立函数中,再以move method将它搬移到需要多态性的那个类里。此时决定是否使用replace type code with subclasses或replace type code with state/strategy。这样完成后就可以使用replace conditional with polymorphism。

如果只是在单一函数中有些选择事例,且并不想改动它们,那么可以使用replace parameter with explicit methods。如果选择条件时,可以尝试introduce null objects

原创粉丝点击