代码之家  ›  专栏  ›  技术社区  ›  jvnill

根据选项调用方法(重构的最佳方式)

  •  0
  • jvnill  · 技术社区  · 13 年前

    我有一个函数,其中我传递一个字符串和一个将其用作正则表达式的选项

    def regexp_this?(string, arg1, arg2, regx = false)
      if regx
        method1 %r{#{string}:someconstantstring}
        method2 %r{#{string}:someconstantstring:#{arg1}}
        method3 %r{#{string}:someconstantstring:#{arg1}:anotherconstant:#{#arg2}}
      else
        method1 "#{string}:someconstantstring"
        method2 "#{string}:someconstantstring:#{arg1}"
        method3 "#{string}:someconstantstring:#{arg1}:anotherconstant:#{#arg2}"
      end
    end
    

    method1 , method2 method3 是对expire_fragment的调用。我正在根据页面的当前状态构建一个缓存。如果已声明或未声明arg1或arg2,则我有不同的缓存密钥需要过期。

    有没有办法重构它?

    2 回复  |  直到 12 年前
        1
  •  2
  •   kristinalim    13 年前

    至少对于有条件的,你应该能够做这样的事情:

    def regexp_this?(string, arg1, arg2, regx = false)
      # Select whether you want a String or Regexp parameter.
      argument_klass = (regx ? Regexp : String)
    
      method1 argument_klass.new("#{string}: ...")
      method2 argument_klass.new("#{string}: ...")
      method3 argument_klass.new("#{string}: ...")
    end
    
        2
  •  0
  •   Andrew Marshall    13 年前

    对于一个方法,您有多个责任,将它们分开并适当命名。一个方法中有一个正则表达式验证、多个参数和多个方法。我推荐阅读 the SOLID principles .

    推荐文章