如何从旧式/怪异模式代码中分离出良好的代码 [英] How to separate good code from legacy/quirks-mode code

查看:71
本文介绍了如何从旧式/怪异模式代码中分离出良好的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到一些实现某些普遍协议或类似协议(例如FTP)的库,我如何将我的符合标准的代码与仅能与不符合标准的系统进行协作的代码分开?

Given some library that implements some widespread protocol or something similar (for instance FTP), how would I keep my standard compliant code separate from code that is only needed to be able to cooperate with not so standard compliant systems?

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

A nice example where this would make sense too IMHO are libraries like jQuery that have to consider all those browser peculiarities. Projects that have to keep legacy compatibility would probably also be a good target audience for such techniques.

我对红宝石解决方案特别感兴趣,但也欢迎使用独立于语言的模式或其他语言的优秀示例.

I'm especially interested in ruby solutions but language independent patterns or good examples from other languages are welcome too.

我已经找到了这里是关于stackoverflow的相关问题,但是还有其他方法吗?

I already found a related question here on stackoverflow, but are there any other approaches?

推荐答案

  1. 为不同的模式定义不同的实现(这使您不必将好的"代码与仅用于保持向后兼容性的代码混合在一起).理想情况下,旧层只是围绕符合标准的代码的包装.
  2. 检测底层系统(浏览器,远程服务器等)符合标准的程度.具体如何完成显然很大程度上取决于具体情况.
  3. 为特定系统选择正确的实现并透明地插入.
  4. 为用户提供检查我们处于哪种模式并强制执行特定模式的机会.

小Ruby示例:

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"

这篇关于如何从旧式/怪异模式代码中分离出良好的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆