Consider the two code segments below. Which one is better and Why? If you have any other idea, please do mention. Where can I find answers to coding p
A switch would be a better solution to your problem I think. You would need to overload the method to take in an int param and I don't know if that's something you would want to do or not.
Bool MyApplication::ReportGenerator::GenerateReport(int i)
{
switch(i)
{
case 1:
// do something
break;
case 2:
// do something
break;
// etc
}
return GeneratReport()
}
Not really sure what your plan is since you're calling the method recursively and as some point you will want to leave the method.
https://computing.llnl.gov/linux/slurm/coding_style.pdf
It really depends on the future expectations of the code. Code1 above implies that there may be additional logic to be added for each of the conditions; Code2 above implies rather that there is a rational grouping of the conditionals. Code1 may be more relevant if you expect to add logic for the conditions at a later date; if you don't, though, Code2 is probably more sensible because of the brevity and implied grouping.
Which on do you think best expresses what the code is trying to say. Which one do you need to work hardest to understand?
I would do this:
bool MyApplication::ReportGenerator::GenerateReport(){
if (isAdmin() && isConditionOne() && isConditionTwo() && isConditionThree()){
return generateReport();
} else {
return false;
}
}
Because:
a). Prefer to say what I want rather than what I don't want b). prefer symmetry, if and else. Clearly all cases covered.
Personally I prefer my for
, while
and do ... while
loops to be actual loops. In the first code example this is not the case. So I would opt for example 2. Or, as others have already said, for breaking example 2 into a number of if ... return
statements.
I like the answers that are a variation of version 2, but just to give an alternative: If those conditions are logically tied together, chances are that you will need to check for them again in other places. If this is true, then maybe a helper function would do the job better. Something like this:
bool isReportable(anyParametersNeeded){
//stuffYouWantToCheck
}
bool MyApplication::ReportGenerator::GenerateReport(){
if (isReportable(anyParametersNeeded)){
return generateReport();
}
return false;
}
As this function is small, maybe you can even inline it (or let the compiler decide ;)). Another bonus is that if you want to include some extra checks in the future, you only have to change that function and not every spot where it's used.