void caller()
{
int var;
var = setvar();
if (var == 1)
func1();
else if (var == 3)
func3();
else if (var == 8)
func8();
}
void func1()
{
common();
//do something case 1 specific...
}
void func3()
{
common();
//do something case 3 specific...
}
void func8()
{
common();
//do something case 8 specific...
}
In this case, I feel very uncomfortable because I have duplicate function common() which could be written inside the caller() function to remove duplicate. So I can change above code like this:
void caller()
{
int var;
var = setvar();
if (var == 1 || var == 3 || var == 8)
common();
if (var == 1)
func1();
else if (var == 3)
func3();
else if (var == 8)
func8();
}
void func1()
{ //do something case 1 specific... }
void func3()
{ //do something case 3 specific... }
void func8()
{ //do something case 8 specific... }
However, I feel very uncomfortable in this case too, because caller() function now check var's value twice.
I don't have much experience of coding, so I don't know what to consider to choose which one is better. What is better code and why? What do I have to consider?