I’ve been coding in c# for a while now and generally have a good idea about the rule of thumb for coding standards. I’ve been recently encourage by my colleges to adopt a results based approach to coding functional blocks rather than nesting blocks of logic and am seeking your advice. Below is an example of what I’m talking about, where the result of one situation is used to determine the code path rather than nesting. It’s been suggested that this approach is easier to read, especially if the result would require several layers of nesting, however I prefer to uses Curly’s Law and refactor methods and functions where nesting becomes to deep.
private void MethodOne()
{
bool CarryOn = false;
// first layer
if (ValidationRuleOne() == true)
{
CarryOn = true;
} else {
CarryOn = false;
}
// second layer
if (CarryOn)
{
CarryOn = ValidationRuleTwo();
} else {
CarryOn = false;
}
// third layer
if (CarryOn)
{
CarryOn = ValidationRuleThree();
} else
{
CarryOn = false;
}
}
This approach just seems wrong to me as I would suggest that the method should be rewriten as ..
private void MethodOne()
{
// first layer
if (ValidationRuleOne() == true)
{
// second layer
if (ValidationRuleTwo() == true)
{
// third layer
if (ValidationRuleThree() == true)
{
}
}
}
}
If the nesting becomes too complex then I would suggest that the method/function structure needs to be rethought to group logical groups of functionality together into additional methods or functions are required?
Any thoughts greatly appreciated.
Regards,
Tim
if (ValidationRuleOne() == true)
{
// second layer
if (ValidationRuleTwo() == true)
{
// third layer
if (ValidationRuleThree() == true)
can be:
if(ValidationRuleOne() && ValidationRuleTwo() && ValidationRuleThree())
{
...
}
in my opinion much easier to read.
and if for some reason you need each validation rule to fire:
if(ValidationRuleOne() & ValidationRuleTwo() & ValidationRuleThree())
{...} //note the & vs &&
(and you don't need to do if(validationRule() == true), since validation returns a boolean, you don't need to compare it to one in a conditional statement).
I personally like using guard clauses.
if (!ValidationRuleOne())
return;
if (!ValidationRuleTwo())
return;
if (!ValidationRuleThree())
return;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With