重构我的if语句代码

mik*_*kew 1 refactoring if-statement pseudocode

我一直在搞乱这段代码一个多小时,试图以不同的方式重新安排它.有没有更简单的方法来写它?

   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   
   }
Run Code Online (Sandbox Code Playgroud)

Chr*_*ich 7

看起来你想要Eval字符串和Scale数字.而不是有四个显式案例(将变为八个有三个变量),处理每个案例xy独立处理:

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

if y is Number
    Scale(y)
else
    Eval(y)
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,您可以推送Eval/ Scale进入实用程序方法:

ScaleOrEval(z):
    if z is Number
        Scale(z)
    else
        Eval(z)
Run Code Online (Sandbox Code Playgroud)

......然后用它......

ScaleOrEval(x)
ScaleOrEval(y)
Run Code Online (Sandbox Code Playgroud)

如果选择好的方法名称,那么创建实用程序方法会使代码更具可读性,并帮助您避免复制和粘贴重复.