Is it ok to skip “return None”?

后端 未结 7 1655
Happy的楠姐
Happy的楠姐 2020-12-03 06:17

I wonder if it is bad manner to skip return None, when it is not needed.

Example:

def foo1(x):
    if [some condition]:
        return B         


        
7条回答
  •  天命终不由人
    2020-12-03 07:03

    The more I think about it, the less I think the case you describe shows good practice. It forces the client to discriminate, so client code would almost always look like:

    b = foo1(123)
    if b is not None:
        ...
    

    You couldn't even write:

    if b:
        ...
    

    since, if Baz.__nonzero__ is overwritten, b could evaluate to False, even if it's not None. It would be better to have a Null-Baz instance (AKA Null Object), e.g.:

    class Baz(object):
        def some_method(self):
            """some action:"""
            ...
        ...
    
    class BazNull(Baz):
        def some_method(self):
            """nothing happens here"""
        ...
    
    Baz.Null = BazNull()
    
    ...
    
    def foo1(x):
        if some_condition:
            return Baz(x)
        else:
            return Baz.Null
    
    ...
    
    b = foo1(123)
    b.some_method()
    

    The point is: help the client (who might be yourself!) to keep Cyclomatic Complexity low. The fewer branches, the better.

提交回复
热议问题