将参数替换为显式方法
问题
一个方法被分成几个部分,每个部分的运行取决于一个参数的值。
解决方案
将方法的各个部分提取到它们自己的方法中,并调用它们,而不是调用原来的方法。
之前
void setValue(字符串名称,int值){if (name.equals("height")) {height = value;返回;} if (name.equals("width")) {width = value;返回;} Assert.shouldNeverReachHere ();}
后
void setHeight(int arg){高度= arg;} void setWidth(int arg){宽度= arg;}
之前
void SetValue(字符串名称,int值){if (name. equals ("height")) {height = value;返回;} if (name.Equals("width")) {width = value;返回;} Assert.Fail ();}
后
void SetHeight(int arg){高度= arg;} void SetWidth(int arg){宽度= arg;}
之前
函数setValue($name, $value) {if ($name === "height") {$this->height = $value;返回;}如果($ name = = =“宽度”){$ this - >宽度=美元价值;返回;} assert(“不应该到达这里”);}
后
function setHeight($arg) {$this->height = $arg;}函数setWidth($arg) {$this->宽度= $arg;}
之前
def output(self, type): if name == "banner" #打印横幅#……if name == "info" #打印信息。#……
后
def outputBanner(self): #打印横幅。#……def outputInfo(self): #打印信息。#……
之前
setValue(名称:字符串,值:数字):无效{if (name.equals("height")){高度=值;返回;} if (name.equals("width")) {width = value;返回;}}
后
setHeight(参数:数字):无效{高度=参数;} setWidth(参数:数字):数字{宽度=参数;}
为什么重构
包含依赖参数的变量的方法已经变得非常庞大。重要的代码在每个分支中运行,很少添加新的变量。
好处
- 提高代码的可读性。的目的更容易理解
难题()
比setValue(“engineEnabled”,真的)
.
什么时候不用
- 如果一个方法很少改变,并且没有在其中添加新的变量,那么不要用显式方法替换参数。
如何重构
对于方法的每个变体,创建一个单独的方法。根据main方法中的参数值运行这些方法。
找到所有调用原始方法的地方。在这些地方,调用一个新的依赖于参数的变量。
当没有对原始方法的调用时,删除它。