由一论坛文章 想到的ocp原则

今天闲来无事去社区上逛了一下。发现一个好帖子,顺便说下个人的意见:

需求是这样的 ,对下面需求做重构:

Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Bob answers 'Sure.' if you ask him a question.
He answers 'Whatever.' if you tell him something.
He answers 'Woah, chill out!' if you yell at him (ALL CAPS).
He says 'Fine. Be that way!' if you address him without actually saying anything.

 from ruby-china  网址:http://ruby-china.org/topics/13178

有一下几种做法:

1.典型的if else判断的 :

class Bob
  def hey(words)
    if words.nil? || words.strip.empty?
      "Fine. Be that way!"
    elsif words.upcase == words
      "Woah, chill out!"
    elsif words[-1] == "?"
      "Sure."
    else
      "Whatever."
    end
  end
end 

2,将if else 部分抽出

class WordsParser
  def silent?(words)
    words.nil? || words.strip.empty?
  end

  def shout?(words)
    words.upcase == words
  end

  def question?(words)
    words.end_with?("?")
  end
end

class Bob
  def hey(words)
    @parser = WordsParser.new

    if @parser.silent?(words)
      "Fine. Be that way!"
    elsif @parser.shout?(words)
      "Woah, chill out!"
    elsif @parser.question?(words)
      "Sure."
    else
      "Whatever."
    end
  end
end

 还有一位做的更加简洁的,我也和喜欢 :

class Bob
  def hey(words)
    return "Fine. Be that way!" if words.nil? || words.strip.empty?
    return "Woah, chill out!" if words.upcase == words
    return "Sure" if words[-1] == "?"
    return  "Whatever."
  end
end

 3但是我最喜欢的还是下面这种 :

class Bob
  Rules = [
    [->w{w.nil? || w.strip.empty?}, 'Fine. Be that way!'],
    [->w{w.upcase == w           }, 'Woah, chill out!'  ],
    [->w{w[-1] == "?"            }, 'Sure.'             ],
    [->w{true                    }, 'Whatever.'         ]
  ]

  def hey(words)
    Rules.each{|checker, answer| return answer if checker.call(words)}
  end
end

 也许你看不出来为什么我最喜欢第三种,但是稍微分析下就发现第三种做法的好处。先不说你能不能看懂lambda表达式,他整体的这样设计就是一种更容易扩展的做法。举个例子来说:现在我添加一种新的功能

Bob answers 'hello world.' if you tell him a programming language . 

那会有怎么样的做法呢?

对于第1种:添加一个elsif 来满足这样的需求 

对于第2种:在WordsParser里面添加一个ifelse 还要在Bob里面添加一个ifelse

对于第3种: 添加一个lumbda表达语句就好了。

下面详细的说下前两种的不好。

对于第1种来说,当年的需求种类少的话,还好说,多几个ifelse就好了。但是当需求大的时候呢,这一个函数里面充满了ifelse(不要笑,我见过一个类里面只有两个函数一个几行的函数,另外一个则都是ifelse)。这时候你会发现他比较大了。应该说可以把他抽成一个模块了。这时候你在去做,可能形成的就是第2种的样式。

对于第2种来说,其实已经很不错了,但是有一个设计原则他却违反了,那就是ocp(open-close-principle),不知道你有没有发现,你每添加一项功能的时候都会修改两个地方,一个是重构出去的函数里面添加一个ifelse。还有在Bob里面添加一个ifelse。ocp所说的就是对修改关闭,对扩展开放。所以来说第三种就是最合适的了。

你可以想象一下。如果扩充功能的话,对于第三种来说是多么的方便。当然在第3种方案里面可以将Rules抽出来作为一个扩展功能类。作为Expression的子类。

最后说一下,有人可能说他本来就懒你还让他做这么多。意思是:用户就这些需求,没有必要扩展,我只能说,我想多了。哈哈。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值