繁体   English   中英

如何消除代码重复?

[英]How to eliminate code repetition?

在以下代码段中,如何减少代码重复:

  if(motionIOS == 0) 
  {
    if(character == 40)
    {
      previousMotion = character;
    }
      if(previousMotion == 40 && character == 50)
      {
        motionIOSValue = 50;
      }
    else
    {
    previousMotion = character;
    }
  }

  if(motionIOS == 1) 
  {
    if(character == 60)
    {
      previousMotion = character;
    }
      if(previousMotion == 60 && character == 70)
      {
        motionIOSValue = 70;
      }
    else
    {
    previousMotion = character;
    }
  }

本质上,我两次执行相同的代码,但是某些事情的值发生了变化。 对于可变数字,我什至甚至需要多次使用此代码。

我想我应该将其重构为一个函数,但不知道如何。

您可以合并条件检查。

if(motionIOS == 0 && previousMotion == 40 && character == 50) {
    motionIOSValue = 50;
} else if (motionIOS == 1 && previousMotion == 60 && character == 70){
    motionIOSValue = 70;
} else {
    previousMotion = character;
}

如果需要,可以将条件检查提取到另一个类。

bool updateIosValue(int previousMotion, int character, int testMotion, int testCharacter){
    //do your custom checks here.
    return previousMotion==testMotion && character== testCharacter;
} 

if(motionIOS==0 && updateIosValue(previousMotion, character, 40, 50){
    motionIOSValue = 50;
}else if(motionIOS==1 && updateIosValue(previousMotion, character, 60, 70){
    motionIOSValue = 70;
}else{
    previousMotion = character;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM