1

Is there any functional difference between the following 2 code snippets?

bool ColorClass::setTo(int inRed, int inGreen, int inBlue)   
{
  amountRed = inRed;                     
  amountGreen = inGreen;
  amountBlue = inBlue;

  return clipColor(amountRed, amountGreen, amountBlue);
}


bool ColorClass::setTo(int inRed, int inGreen, int inBlue)   
{
  amountRed = inRed;                     
  amountGreen = inGreen;
  amountBlue = inBlue;

  if (clipColor(amountRed, amountGreen, amountBlue))
  {
    return true;
  }
  else 
  {
    return false;
  }
}

The functions the above code calls are defined below:

bool ColorClass::clipColor(int &checkRed, int &checkGreen, int &checkBlue) 
{
  int numClips = 0;     //numClips is used to counter number of clips made
  checkColorBounds(checkRed, numClips);
  checkColorBounds(checkGreen, numClips );
  checkColorBounds(checkBlue, numClips);
  return (numClips != 0);
}
void ColorClass::checkColorBounds(int &color, int &clipCounter)
{
  if(color > MAXCOLOR)
  {
    color = MAXCOLOR; 
    clipCounter++;
  }
  else if (color < MINCOLOR)
  {
    color = MINCOLOR;
    clipCounter ++;
  }
}

I tested both and gone through both, and I can't seem to notice anything functionally different.

I like the first one better, because it is much more succint and more efficient (avoids the if-else)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
David
  • 619
  • 2
  • 8
  • 15

1 Answers1

0

There're no any functional differences at all. Then use the 1st one.

KISS

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thanks. Are you suggesting to use the first one because it is more efficient (I suspect it is more sufficient, though I am not sure). – David Feb 15 '16 at 07:50
  • @David It's hard to say that, until measuring precisely. But I think it won't change much on modern compilers. – songyuanyao Feb 15 '16 at 07:54
  • @David [When is optimisation premature?](http://stackoverflow.com/q/385506/3309790) – songyuanyao Feb 15 '16 at 08:02