What is Replace Conditional with Polymorphism Refactoring? How is it implemented in Ruby? -
i came across replace conditional polymorphism refactoring while asking elimination of if..else conditional in ruby.the link
can explain me how can implement same in ruby?(a simple sweet code do)
the replace conditional polymorphism refactoring rather simple , pretty sounds like. have method conditional this:
def speed case @type when :european base_speed when :african base_speed - load_factor * @number_of_coconuts when :norwegian_blue if nailed? 0 else base_speed(@voltage) end end and replace polymorphism this:
class european def speed base_speed end end class african def speed base_speed - load_factor * @number_coconuts end end class norwegianblue def speed if nailed? 0 else base_speed(@voltage) end end you can apply refactoring again norwegianblue#speed creating subclass of norwegianblue:
class norwegianblue def speed base_speed(@voltage) end end class nailednorwegianblue < norwegianblue def speed 0 end end voilà, conditionals gone.
you might ask yourself: always work? can always replace if message dispatch? , answer is: yes, can! in fact, if didn't have if, can implement using nothing message dispatch. (this is, in fact, how smalltalk it, there no conditionals in smalltalk.)
class trueclass def iff(thn:, els: ->{}) thn.() end def & yield end def | self end def ! false end end class falseclass def iff(thn:, els: ->{}) els.() end def & self end def | yield end def ! true end end (3 > 4).iff(thn: ->{ 'three bigger four' }, els: ->{ 'four bigger three' } ) # => 'four bigger three' true.& { puts 'hello' } # hello true.| { puts 'hello' } # => true also relevant: anti-if campaign
Comments
Post a Comment