我有一个遗留代码,它根据开关语句中的情况对不同的类执行相同的工作。
是否有可能在下面的switch语句中减少代码逻辑重复?
我有三个班长颈鹿,猎犬和动物。长颈鹿和猎犬都是扩张动物。
public class Animal {
int sleepDuration
int noOfLegs;
public setNoOfLegs(int noOfLegs) {
this.noOfLegs = noOfLegs;
}
public setSleepDuration(int sleepDuration) {
this.sleepDuration = sleepDuration
}
public getSleepDuration() {
return this.sleepDuration;
}
public getNoOfLegs() {
return this.noOfLegs;
}
}
class Hound extends Animal {
// some hound specific variables and functions here
}
class Giraffe extends Animal{
// some giraffe specific variables and functions here
}
public class Jungle {
public someMethod(String caseString) {
Animal animal = JacksonMapper.convertBytesToType(animalbyteContent, Animal.class);
switch (caseString) {
case "giraffe":
Giraffe giraffe = JacksonMapper.convertBytesToType(contentInBytes, Giraffe.class);
giraffe.setSleepDuration(animal.getSleepDuration);
giraffe.setNoOfLegs(animal.getNoOfLegs);
break;
case "hound":
Hound hound = JacksonMapper.convertBytesToType(contentInBytes, Hound.class);
hound.setSleepDuration(animal.getSleepDuration);
hound.setNoOfLegs(animal.getNoOfLegs);
break;
default :
log.error("Hurray!! You discovered a new animal species");
}
}发布于 2015-02-18 08:02:41
我不明白为什么你第一次投给动物,但无论如何,我能推荐的最简单的重构是提取到方法。setSleepDuration和setSleepDuration是共享的,因此您可以创建一个接受两种动物的方法:
Giraffe giraffe = JacksonMapper.convertBytesToType(contentInBytes, Giraffe.class);
setAnimalFields(giraffe, animal);setAnimalFields在哪里
public void setAnimalFields(Animal newAnimal, Animal oldAnimal){
newAnimal.setSleepDuration(oldAnimal.getSleepDuration);
newAnimal.setNoOfLegs(oldAnimal.getNoOfLegs);
}https://stackoverflow.com/questions/28571439
复制相似问题