首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中删除逻辑复制

在Java中删除逻辑复制
EN

Stack Overflow用户
提问于 2015-02-17 21:30:08
回答 1查看 75关注 0票数 0

我有一个遗留代码,它根据开关语句中的情况对不同的类执行相同的工作。

是否有可能在下面的switch语句中减少代码逻辑重复?

我有三个班长颈鹿,猎犬和动物。长颈鹿和猎犬都是扩张动物。

代码语言:javascript
复制
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");
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-18 08:02:41

我不明白为什么你第一次投给动物,但无论如何,我能推荐的最简单的重构是提取到方法。setSleepDurationsetSleepDuration是共享的,因此您可以创建一个接受两种动物的方法:

代码语言:javascript
复制
   Giraffe giraffe = JacksonMapper.convertBytesToType(contentInBytes, Giraffe.class);

setAnimalFields(giraffe, animal);

setAnimalFields在哪里

代码语言:javascript
复制
public void setAnimalFields(Animal newAnimal, Animal oldAnimal){
         newAnimal.setSleepDuration(oldAnimal.getSleepDuration);
         newAnimal.setNoOfLegs(oldAnimal.getNoOfLegs);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28571439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档