I have read some code and here are two ways to check and log the error in cpp co
ID: 652697 • Letter: I
Question
I have read some code and here are two ways to check and log the error in cpp code that repeats in my project many times. Which way is better?
1.
bool AClass::myMethod()
{
if (!SomeCondition())
{
Warning("AClass::myMethod: your description");
return false;
}
doSomthing();
return true;
}
2.
bool AClass::myMethod()
{
if (SomeCondition())
{
doSomething();
}
else
{
Warning("AClass::myMethod? your description");
return false;
}
return true;
}
Explanation / Answer
I think that in this specific case, both solutions are equally well readable.
However, if there are other checks added later to verify that the function can continue to process, then only the first solution will be easily extended without making the code difficult to follow:
bool AClass::myMethod()
{
if (!SomeCondition())
{
Warning("AClass::myMethod: your description");
return false;
}
if (!SomeCondition2())
{
Warning("AClass::myMethod: another description");
return false;
}
doSomthing();
return true;
}
is clearer than
bool AClass::myMethod()
{
if (SomeCondition())
{
if(SomeOtherCondition())
{
doSomething();
}
else
{
Warning("AClass::myMethod? another description");
return false;
}
}
else
{
Warning("AClass::myMethod? your description");
return false;
}
return true;
}
So I would personally use the first version as soon as more than one check is necessary.