我将如何重构此 C 代码以消除重复

How would I refactor this C code to get rid of repetition

我正在为微控制器编写驱动程序以连接传感器。我使用的传感器是 MAG3110。我写了一个可以控制传感器上所有东西的驱动程序,但是有很多代码重复。四分之三的函数采用以下形式:

 uint8_t ReadWhoAmI(uint8_t *readPtr)
 { 
    return MagReadByte(WHO_AM_I, readPtr);
 }

uint8_t SetSingleMeasurmentMode()
{
    uint8_t currentReg1Flags;
    ReadCtrlReg1(&currentReg1Flags);

    currentReg1Flags &= 0xFC; 
    currentReg1Flags |= CTRL_REG1_SINGLE_MEASURMENT; 

    return WriteCtrlReg1(currentReg1Flags);
}

如何概括这些函数?我知道在函数式编程中我会简单地参数化函数,但我不知道如何在 C 中应用类似的概念。

您可以通过以下方式获得 SetSingleMeasurmentMode 的通用版本:

uint8_t SetSingleMeasurmentModeGen(void (*ReadFunction)(uint8_t*),
                                   void (*WriteFunction)(uint8_t))
{
    uint8_t currentReg1Flags;
    ReadFunction(&currentReg1Flags);

    // Assuming this logic remains same.
    currentReg1Flags &= 0xFC; 
    currentReg1Flags |= CTRL_REG1_SINGLE_MEASURMENT; 

    return WriteFunction(currentReg1Flags);
}

并使用:

uint8_t SetSingleMeasurmentMode()
{
    return SetSingleMeasurmentModeGen(ReadCtrlReg1, WriteCtrlReg1);
}

如果更改标志值的逻辑不相同,则需要传递另一个函数。

uint8_t SetSingleMeasurmentModeGen(void (*ReadFunction)(uint8_t*),
                                   uint8_t (*TransformFlag)(uint8_t),
                                   void (*WriteFunction)(uint8_t))
{
    uint8_t currentReg1Flags;
    ReadFunction(&currentReg1Flags);    
    return WriteFunction(TransformFlag(currentReg1Flags));
}

uint8_t TransformFlag1(uint8_t flag)
{
    flag &= 0xFC; 
    flag |= CTRL_REG1_SINGLE_MEASURMENT; 
    return flag;
}

uint8_t SetSingleMeasurmentMode()
{
    return SetSingleMeasurmentModeGen(ReadCtrlReg1, TransformFlag1, WriteCtrlReg1);
}