我有一个遗留代码,它基于switch语句中的case在不同的类上执行相同的工作。
是否可以减少下面的switch语句中的代码逻辑重复?
我有3个班级长颈鹿,猎犬和动物。长颈鹿和猎犬这两个类都扩展了动物。
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");
}
}
答案 0 :(得分:0)
我不明白你为什么首先向Animal施放,但无论如何,我能推荐的最简单的重构是提取方法。共享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);
}