如下:有时会遇到这种重复的new创建
public class Item {
public String name;
public int sellIn;
public int quality;
public Item(String name, int sellIn, int quality) {...}
Item[] items = new Item[] {
new Item("+5 Dexterity Vest", 10, 20),
new Item("Aged Brie", 2, 0),
new Item("Elixir of the Mongoose", 5, 7),
new Item("Sulfuras, Hand of Ragnaros", 0, 80),
new Item("Sulfuras, Hand of Ragnaros", -1, 80),
new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20),
new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49),
new Item("Backstage passes to a TAFKAL80ETC concert", 5, 49),
new Item("Backstage passes to a TAFKAL80ETC concert", 1, 20),
new Item("Conjured Mana Cake", 3, 6)
};
问题:这种代码很显然是一种坏味道,充斥了大量的重复,那如何解决呢?
解决方式:将创建的方式抽取为方法,并且移动到属于他的类
具体步骤:
- 提炼变量(找到重复的地方)
由于他后面的两个值,是会变化的,因此应当抽取出来,这样后面提炼为方法的时候,就会将他们两个作为参数,可以参考步骤2理解原因
int sellIn = 0;
int quality = 80;
Item[] items = new Item[] {
new Item("Sulfuras, Hand of Ragnaros", sellIn, quality),
...
};
- 提炼方法
Item[] items = new Item[] {
...
getItem(sellIn, quality),
...
};
private static Item getItem(int sellIn, int quality) {
return new Item("Sulfuras, Hand of Ragnaros", sellIn, quality);
}
- 移动方法(可选,如果这个方法就属于这个类的职责,则不需要变动)
public class Item {
public String name;
public int sellIn;
public int quality;
public Item(String name, int sellIn, int quality) {...}
static Item getItem(int sellIn, int quality) {
return new Item("Sulfuras, Hand of Ragnaros", sellIn, quality);
}
- 将变量内联
Item[] items = new Item[] {
...
Item.getItem(0, 80),
...
}
- 尝试如上4个步骤,对其他的创建,进行一个重构
示例来源
关于:提炼变量、提炼方法、内联、移动方法 快捷键使用参考此文档
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)