我将如何重构此C代码以摆脱重复

时间:2015-03-03 19:47:39

标签: c refactoring

我正在为微控制器编写驱动程序以与传感器连接。我使用的传感器是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中应用类似的概念。

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容获得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);
}