推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
rogwan
V2EX  ›  Python

用函数封装那些过于复杂的逻辑判断

  •  
  •   rogwan · Jan 20, 2019 · 2643 views
    This topic created in 2871 days ago, the information mentioned may be changed or developed.

    如果条件分支里的表达式过于复杂,出现了太多的 not/and/or,那么这段代码的可读性就会大打折扣,比如下面这段代码:

    # 如果活动还在开放,并且活动剩余名额大于 10,为所有性别为女性,或者级别大于 3
    # 的活跃用户发放 10000 个金币
    if activity.is_active and activity.remaining > 10 and \
            user.is_active and (user.sex == 'female' or user.level > 3):
        user.add_coins(10000)
        return
    

    对于这样的代码,我们可以考虑将具体的分支逻辑封装成函数或者方法,来达到简化代码的目的:

    if activity.allow_new_user() and user.match_activity_condition():
        user.add_coins(10000)
        return
    

    事实上,将代码改写后,之前的注释文字其实也可以去掉了。因为后面这段代码已经达到了自说明的目的。至于具体的 什么样的用户满足活动条件? 这种问题,就应由具体的 match_activity_condition() 方法来回答了。


    Hint: 恰当的封装不光直接改善了代码的可读性,事实上,如果上面的活动判断逻辑在代码中出现了不止一次的话,封装更是必须的。不然重复代码会极大的破坏这段逻辑的可维护性。

    编写条件分支代码的技巧

    5 replies  •  2019-01-21 16:27:12 +08:00
    j2gg0s
    j2gg0s
    Jan 20, 2019
    1
    According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes.
    ericls
    ericls
    Jan 21, 2019
    2
    如果没有需要重用,避免过早优化
    这种问题只要整个 team 统一用一个 formatter 和配置 就好, 比如 black
    wdv2ly
    wdv2ly
    Jan 21, 2019 via Android
    3
    编程基础第一节就没必要科普了吧?
    nekoneko
    nekoneko
    Jan 21, 2019
    4
    二楼说得对
    xpresslink
    xpresslink
    Jan 21, 2019
    5
    谢谢楼主不辞辛劳从火星赶来告诉大家大清忘了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4679 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 01:57 · PVG 09:57 · LAX 17:57 · JFK 20:57
    ♥ Do have faith in what you're doing.