开发者

refactor my if statement code

开发者 https://www.devze.com 2023-01-13 07:57 出处:网络
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?

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开发者_StackOverflow      ;// 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   
   }


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.


// 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
0

精彩评论

暂无评论...
验证码 换一张
取 消