Say, in C, I have 2 methods that are completely identical, but 1 adds a value, and the other produces it:
void decreaseValue(handle* myData, uint8_t amount)
{
myData->someAttribute -= amount;
}
void increaseValue(handle* myData, uint8_t amount)
{
myData->someAttribute += amount;
}
With the exception of operators, both functions are completely identical, resulting in quite a few lines of duplicated code, which is not trivial.
Is there a safe, portable, not ugly way to handle this, or am I stuck in ctrl + c ctrl + v?
Switch Flag Potential:
typedef enum
{
ADD,
SUBSTRACT
}operator;
void modifyValue(handle* myData, uint8_t amount, operator op)
{
switch(op){
case ADD:
myData->someAttribute += amount;
break;
case SUBSTRACT:
myData->someAttribute -= amount;
break;
}
It works, but does not feel better.
Asics source
share