[C 的那些眉角]一個函式只做一件事 — 聽起來簡單但很難

「一個函式只做一件事。」

這句話我很早就聽過,覺得自己懂了,然後繼續寫出這種東西:

int process_sensor_data(void) {
    // 讀取感測器
    uint8_t raw[8];
    i2c_read(SENSOR_ADDR, raw, sizeof(raw));

    // 解析資料
    int16_t temp = (raw[0] << 8) | raw[1];
    int16_t humidity = (raw[2] << 8) | raw[3];

    // 換算單位
    float temp_c = temp / 100.0f;
    float humi_pct = humidity / 100.0f;

    // 檢查是否超過閾值
    if (temp_c > 85.0f || humi_pct > 95.0f) {
        trigger_alarm();
    }

    // 存到全域變數
    g_temperature = temp_c;
    g_humidity = humi_pct;

    // 發送到 server
    mqtt_publish("sensor/data", temp_c, humi_pct);

    return 0;
}

這個函式做了幾件事?

讀取、解析、換算、判斷、存值、發送。六件事。

當時覺得「這樣寫很方便,一個函式搞定所有事情」。
直到需要修改的時候才發現,牽一髮動全身,
改個閾值要找半天,加個錯誤處理不知道要加在哪裡,
單元測試根本不知道從哪裡下手。

閱讀全文