avoiding if statements

前端 未结 24 734
心在旅途
心在旅途 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)
    <class Number>
    >>> type(3+3)
    <class GreaterThan5>
    >>> 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.

    0 讨论(0)
  • 2021-01-30 09:18

    Creating a whole new class for an else, while technically doable, would likely result in code that is hard to read, maintain, or even prove correct.

    0 讨论(0)
  • 2021-01-30 09:19

    It depends on what the original statement is comparing. My rule of thumb is that if it's a switch or if testing equality against an enumeration, then that's a good candidate for a separate method. However, switch and if statements are used for many, many other kinds of tests -- there's no good way to replace the relational operators (<, >, <=, >=) with specialized methods, and some kinds of enumerated tests work much better with standard statements.

    So you should only replace ifs if they look like this:

    if (obj.Name == "foo" || obj.Name == "bar") { obj.DoSomething(); }
    else if (obj.Name == "baz") { obj.DoSomethingElse(); }
    else { obj.DoDefault(); }
    
    0 讨论(0)
  • 2021-01-30 09:19

    I think applying that argument to the idea of every if statement is pretty extreme, but some languages give you the ability to apply that idea in certain scenarios.

    Here's a sample Python implementation I wrote in the past for a fixed-sized deque (double-ended queue). Instead of creating a "remove" method and having if statements inside it to see if the list is full or not, you just create two methods and reassign them to the "remove" function as needed.

    The following example only lists the "remove" method, but obviously there are "append" methods and the like also.

    class StaticDeque(collections.deque):
    
        def __init__(self, maxSize):
    
            collections.deque.__init__(self)
            self._maxSize = int(maxSize)
            self._setNotFull()
    
        def _setFull(self):
    
            self._full = True
            self.remove = self._full_remove
    
        def _setNotFull(self):
    
            self._full = False
            self.remove = self._not_full_remove
    
        def _not_full_remove(self,value):
    
            collections.deque.remove(self,value)
    
        def _full_remove(self,value):
    
            collections.deque.remove(self,value)
            if len(self) != self._maxSize and self._full:
                self._setNotFull()
    

    In most cases it's not that useful of an idea, but sometimes it can be helpful.

    0 讨论(0)
  • 2021-01-30 09:20

    I can tell you one thing. No matter what people say, thinking about simplifying and eliminating unnecessary branching is a sign of you maturing as a software developer. There are many reasons why branching is bad, testing, maintenance, higher rate of bugs and so on. This is one of the things I look for when interviewing people and is an excellent indicator how mature they are as a developer. I would encourage you to keep experimenting, simplifying your code and design by using less conditions. When I did this switch I found much less time debugging my code, it simply worked, then when I had to change something, changes were super easy to make since most of the code was sequential. Again I would encourage you 100% to keep doing what you are doing no matter what other people say. Keep in mind most developers are working and thinking at much lower level and just follow the rules. So good job bringing this up.

    0 讨论(0)
  • 2021-01-30 09:22

    Yes its true that often complex conditionals can be simplified with polymorphishm. But its not useful all the time. Go read Fowler's Refactoring book to get an idea of when.

    http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html

    0 讨论(0)
提交回复
热议问题