如何将好的代码与传统/怪癖模式代码分开

rap*_*sse 5 language-agnostic legacy-code

鉴于一些库,实现了一些广泛的协议或类似的(例如FTP)的东西,我怎么会保持我的标准兼容的代码单独从只需要能够与不那么符合标准的系统进行合作的代码?

一个很好的例子,这也是有意义的恕我直言,像jQuery这样的库必须考虑所有这些浏览器的特性.必须保持传统兼容性的项目可能也是这些技术的良好目标受众.

我对ruby解决方案特别感兴趣,但也欢迎语言无关的模式或来自其他语言的好例子.

我已经在stackoverflow上找到了一个相关的问题,但还有其他方法吗?

Nik*_* B. 3

  1. 为不同的模式定义不同的实现(这可以防止您必须将“好的”代码与只是为了保持向后兼容性的代码混合在一起)。理想情况下,遗留层只是符合标准的代码的包装器。
  2. 检测底层系统(浏览器、远程服务器等)符合标准的程度。具体如何完成显然很大程度上取决于具体情况。
  3. 为特定系统选择正确的实现并透明地将其插入。
  4. 让用户有机会检查我们所处的模式并强制使用特定模式。

小红宝石示例:

class GoodServer
  def calculate(expr)
    return eval(expr).to_s
  end
end

class QuirkyServer
  def calculate(expr)
    # quirky server prefixes the result with "result: "
    return "result: %s" % eval(expr)
  end
end

module GoodClient
  def calculate(expr)
    @server.calculate(expr)
  end
end

# compatibility layer
module QuirkyClient
  include GoodClient
  def calculate(expr)
    super(expr).gsub(/^result: /, '')
  end
end

class Client
  def initialize(server)
    @server = server
    # figure out if the server is quirky and mix in the matching module
    if @server.calculate("1").include?("result")
      extend QuirkyClient
    else
      extend GoodClient
    end
  end
end

good_server = GoodServer.new
bad_server = QuirkyServer.new

# we can access both servers using the same interface
client1 = Client.new(good_server)
client2 = Client.new(bad_server)

p client1.is_a? QuirkyClient # => false
p client1.calculate("1 + 2") # => "3"

p client2.is_a? QuirkyClient # => true
p client2.calculate("1 + 2") # => "3"
Run Code Online (Sandbox Code Playgroud)