refactor my if statement code

Tag: refactoring , if-statement , pseudocode Author: qqickguang Date: 2010-08-10

I've been messing with this bit of code for over an hour trying to rearrange it different ways. Is there any easier way to write it?

   if x is not Number      ;// if x is string
   {
      if y is not Number      ;// x, y both strings
      {
         Eval(x)
         Eval(y)
         return
      }
      else                    ;// x is string, y is Number
      {
         Eval(x)
         Scale(y)
         return
      }
   }
   else if y is not Number    ;// x is Number, y is string
   {
      Scale(x)
      Eval(y)
      return
   }
   else                       ;// both are numbers
   {
      Scale(x)
      Scale(y)
      return   
   }

Best Answer

It looks like you want to Eval strings and Scale numbers. Instead of having four explicit cases (which would become eight with three variables), handle each case for x and y independently:

if x is Number
    Scale(x)
else
    Eval(x)

if y is Number
    Scale(y)
else
    Eval(y)

Or, better yet, you can push Eval/Scale into a utility method:

ScaleOrEval(z):
    if z is Number
        Scale(z)
    else
        Eval(z)

...and then use it...

ScaleOrEval(x)
ScaleOrEval(y)

If you pick good method names, then creating a utility method makes the code more readable and helps you avoid copy-and-paste repetition.

comments:

2 seconds faster...
Thanks, I thought this was my utility function, named GetScaledButtonCoord. I'm only ever going to have two vars x,y, but maybe I should separate that out further..

Other Answer1

// First handle x
if x is Number
{
    Scale(x)
}
else
{
    Eval(x)
}

// Then handle y
if y is Number
{
    Scale(y)
}
else
{
    Eval(y)
}

return