让我们说在CI中有2个完全相同的方法但是1加上值而另一个加法它:
void decreaseValue(handle* myData, uint8_t amount)
{
/* Stuff going on */
myData->someAttribute -= amount;
/* Stuff going on */
}
void increaseValue(handle* myData, uint8_t amount)
{
/* Stuff going on */
myData->someAttribute += amount;
/* Stuff going on */
}
Run Code Online (Sandbox Code Playgroud)
除了运算符之外,这两个函数完全相同,导致相当多的重复代码行不是微不足道的.
是否有安全,便携,非丑陋的处理方式,或者我坚持使用ctrl + c ctrl + v?
开关盒的可能性:
typedef enum
{
ADD,
SUBSTRACT
}operator;
void modifyValue(handle* myData, uint8_t amount, operator op)
{
/* Stuff going on */
switch(op){
case ADD:
myData->someAttribute += amount;
break;
case SUBSTRACT:
myData->someAttribute -= amount;
break;
/* Stuff going on */
}
Run Code Online (Sandbox Code Playgroud)
它有效,但感觉不到更好.
这个怎么样:
static inline void changeValue(handle* myData, int amount)
{
/* Stuff going on */
myData->someAttribute += amount;
/* Stuff going on */
}
void increaseValue(handle* myData, uint8_t amount)
{
changeValue(myData, (int)amount);
}
void decreaseValue(handle* myData, uint8_t amount)
{
changeValue(myData, -(int)amount);
}
Run Code Online (Sandbox Code Playgroud)