Terjemahkan halaman ini

Reducing Function Size

Function like this is problematic:

from somewhere import Order, get_item


def make_order(data):
    if not data["sku"]:
        raise Exception("'sku' must be present")

    item = get_item(data["sku"])
    if not item:
        raise Exception("item does not exist")

    order = Order(data["sku"], data["amount"])
    order.send_invoice()

    return order

It tried to do everything at once, which makes it harder to test.

Solution

We should break it into multiple, smaller functions:

from somewhere import Order, get_item


def validate_payload(data):
    if not data["sku"]:
        raise Exception("'sku' must be present")


def check_item_availability(sku):
    item = get_item(sku)
    if not item:
        raise Exception("item does not exist")


def create_order(sku):
    order = Order(sku)
    order.send_invoice()
    return order


def make_order(data):
    validate_payload(data)
    check_item_availability(data["sku"])
    return create_order(data["sku"])

Takeaways

Smaller functions have the following advantages:

  • Obvious logic; the program would be much easier to understand.
  • Less bug.
  • Easier to test.