Tính dễ đọc là quan trọng

Nguyên tắc Kỹ thuật Phần mềm với Python

Adam Spannbauer

Machine Learning Engineer

Thiền Python

import this
The Zen of Python, by Tim Peters (rút gọn)

Đẹp tốt hơn xấu.
Tường minh tốt hơn ngầm định.
Đơn giản tốt hơn phức tạp.
Phức tạp tốt hơn rắc rối.
Tính dễ đọc là quan trọng.
Nếu triển khai khó giải thích, đó là ý tưởng tồi.
Nếu triển khai dễ giải thích, đó có thể là ý tưởng hay.
Nguyên tắc Kỹ thuật Phần mềm với Python

Đặt tên mô tả

Đặt tên kém

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

Đặt tên mô tả

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

Quá đà

def check_if_temperature_is_above_boiling_point(
        temperature_to_check, 
        celsius_water_boiling_point=100):
    return temperature_to_check >= celsius_water_boiling_point
Nguyên tắc Kỹ thuật Phần mềm với Python

Giữ mọi thứ đơn giản

The Zen of Python, by Tim Peters (rút gọn)

Đơn giản tốt hơn phức tạp.
Phức tạp tốt hơn rắc rối.

  Miếng pizza

Nguyên tắc Kỹ thuật Phần mềm với Python

Làm pizza - phức tạp

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)
    ...
Nguyên tắc Kỹ thuật Phần mềm với Python

Làm pizza - đơn giản

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

    return bake(assembled_pizza)
Nguyên tắc Kỹ thuật Phần mềm với Python

Khi nào nên refactor

Đặt tên kém

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

Đặt tên mô tả

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

Quá đà

def check_if_temperature_is_above_boiling_point(
        temperature_to_check, 
        celsius_water_boiling_point=100):
    return temperature_to_check >= celsius_water_boiling_point
Nguyên tắc Kỹ thuật Phần mềm với Python

Vamos praticar!

Nguyên tắc Kỹ thuật Phần mềm với Python

Preparing Video For Download...