avoiding if statements

前端 未结 24 1422
心在旅途
心在旅途 2021-01-30 08:39

I was thinking about object oriented design today, and I was wondering if you should avoid if statements. My thought is that in any case where you require an if statement you ca

24条回答
  •  忘掉有多难
    2021-01-30 09:16

    You must understand what (x > 5) really mean. Assuming that x represents a number, then it basically "classifies" all numbers greater than five. So the code would look like this in a language with python syntax:

    class Number(Object):
    
        # ... Number implementation code ... #
    
        def doSomething():
            self = 0
            return self
    
        def doSomethingElse():
            pass
    
    class GreaterThan5(Number):
        def doSomething():
            print "I am " + self
    
        def doSomethingElse():
            print "I like turtles!"
    

    Then we could run code like the following:

    >>> type(3)
    
    >>> type(3+3)
    
    >>> 3.doSomething()
    0
    >>> (3 + 3).doSomething()
    I am 6
    >>> (7 - 3).doSomethingElse()
    >>>
    

    The automatic type conversion here is important. As far as I am aware, none of the languages today allow you to mess with integers this much.

    In the end, you can do in your code whatever. As long as the people reading it can understand immediately. So the polymorphic dispatch on integers or anything unordinary must have really good reasoning behind it.

提交回复
热议问题