Sandi Metz says in SOLID OOPS concepts from GORUCO that presence of if..else
blocks in Ruby can be considered to be a deviation from Open-Close Principle. What all methods can be used to avoid not-urgent if..else
conditions? I tried the following code:
class Fun
def park(s=String.new)
puts s
end
def park(i=Fixnum.new)
i=i+2
end
end
and found out that function overloading does not work in Ruby. What are other methods through which the code can be made to obey OCP?
I could have simply gone for:
class Fun
def park(i)
i=i+2 if i.class==1.class
puts i if i.class=="asd".class
end
end
but this is in violation to OCP.
Look at the is_a? method
But even better not to check a type, but use duck typing:
UPD: After reading comments. Yes, both examples above don't solve the OCP problem. That is how I would do it: