4

I have a rather complex method which can get called in two possible "scenarios". One is a special case of the other in which all the nested foreach loops are only executed once and several if statements are false such that essentially only two lines of code nested deeply inside the method are actually executed.

Now the question is: Should I provide a separate (simpler) code path for the special case even though the complex code handles that case just as well?

I suppose the code would be more readable/understandable that way but I don't want to give the impression that the two cases are handled differently.

Performance is not an issue here so the fact that a simpler code path might also execute faster is negligible.

Example code:

foreach(...)
{
    foreach(...)
    {
    ...
        if(...)
        {
            ...
        }

        Something();
    }
}

as compared to

if(SpecialCase)
{
    Something();
}
else
{
    foreach(...)
    {
        foreach(...)
        {
        ...
            if(...)
            {
                ...
            }

            Something();
        }
    }
}
5

By essentially duplicating some logic you create redundancy. This is an opportunity for bugs.

I suppose the code would be more readable/understandable that way

No, because now readers have to understand one more thing than previously. They still have to understand the full algorithm to see what happens in case !SpecialCase.

I don't want to give the impression that the two cases are handled differently

Well, you are giving that impression. This is going to be confusing to others.

Consider just adding a comment:

"In case of SpecialCase the following algorithm is equivalent to Something();"

0

To me it would be a balance of costs. Would the extra development & maintenance cost be justified by the saved run-time cost? You say "performance is not an issue," so you would be increasing expenditure with no payback. Don't do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.