avoiding if statements

前端 未结 24 1092
心在旅途
心在旅途 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: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.

提交回复
热议问题