What is Replace Conditional with Polymorphism Refactoring? How is it implemented in Ruby?

后端 未结 2 903
清歌不尽
清歌不尽 2021-01-20 14:43

I recently came across the Replace Conditional with Polymorphism Refactoring while asking for elimination of if..else conditional in ruby.the l

2条回答
  •  攒了一身酷
    2021-01-20 15:16

    I think I would format the bolded phrase a little differently, i.e.: Refactor your code to replace the conditional with polymorphism.

    If that is indeed what the comment is supposed to mean, then Yehuda Katz has a great post giving an example in ruby: http://yehudakatz.com/2009/10/04/emulating-smalltalks-conditionals-in-ruby/

    Basically, the argument is that an if/else statement exists to execute different code based on the value of a boolean. It requires special syntax, and is limited to only the types TrueClass/FalseClass (or Object/NilClass if you're being lax about truthiness). Dynamic dispatch on the other hand performs the same operation of selecting branches of code to execute based on the value of an object, but it does not rely on specialized syntax, nor is it limited to any specific group of types.

提交回复
热议问题