可讀性很重要

Python 的軟體工程原則

Adam Spannbauer

Machine Learning Engineer

Python 之禪

import this
The Zen of Python, by Tim Peters (abridged)

優美勝於醜陋。
明確勝於隱晦。
簡單勝於複雜。
複雜勝於繁瑣。
可讀性很重要。
若實作難以解釋,就是壞主意。
若實作容易解釋,可能是好主意。
Python 的軟體工程原則

清楚描述的命名

命名不佳

def check(x, y=100):
    return x >= y

描述清楚的命名

def is_boiling(temp, boiling_point=100):
    return temp >= boiling_point

過度冗長

def check_if_temperature_is_above_boiling_point(
        temperature_to_check, 
        celsius_water_boiling_point=100):
    return temperature_to_check >= celsius_water_boiling_point
Python 的軟體工程原則

保持簡單

The Zen of Python, by Tim Peters (abridged)

簡單勝於複雜。
複雜勝於繁瑣。

  披薩切片

Python 的軟體工程原則

做披薩-複雜版

def make_pizza(ingredients):
    # Make dough
    dough = mix(ingredients['yeast'],
                ingredients['flour'],
                ingredients['water'],
                ingredients['salt'],
                ingredients['shortening'])

    kneaded_dough = knead(dough)
    risen_dough = prove(kneaded_dough)

    # Make sauce
    sauce_base = sautee(ingredients['onion'],
                                ingredients['garlic'],
                                ingredients['olive oil'])

    sauce_mixture = combine(sauce_base,
                            ingredients['tomato_paste'],
                            ingredients['water'],
                            ingredients['spices'])

    sauce = simmer(sauce_mixture)
    ...
Python 的軟體工程原則

做披薩-簡潔版

def make_pizza(ingredients):
    dough = make_dough(ingredients)
    sauce = make_sauce(ingredients)
    assembled_pizza = assemble_pizza(dough, sauce, ingredients)

    return bake(assembled_pizza)
Python 的軟體工程原則

何時重構

命名不佳

def check(x, y=100):
    return x >= y

描述清楚的命名

def is_boiling(temp, boiling_point=100):
    return temp >= boiling_point

過度冗長

def check_if_temperature_is_above_boiling_point(
        temperature_to_check, 
        celsius_water_boiling_point=100):
    return temperature_to_check >= celsius_water_boiling_point
Python 的軟體工程原則

一起來練習吧!

Python 的軟體工程原則

Preparing Video For Download...