简体   繁体   中英

How to eliminate code repetition?

How can I reduce code repetition in the following snippet:

  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;
    }
  }

In essence I am doing the same code twice, but with the values changes for some things. I will even need to use this code many more times too with variable numbers.

I think I should refactor it into a function, but do not know how.

you can consolidate your condition checks.

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

You can extract the condition check to another class if you want.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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