You seem to be concerned with code readability and maintainability. Code blocks like this:
if (someCondition)
{
// do
// a
// lot
{
// moar
// nesting
}
}
else
{
// do
// something
// else
{
// possibly with even more nesting
}
}
are generally considered neither readable nor maintainable. Sure, you can then abuse syntax or use other tricks to reduce the level of nesting, but the fact that you have so much nesting should be a dead giveaway that a method is doing too much.
At least extract the code blocks into their own methods, automatically reducing the nesting.
If you place the above code in its own method to begin with, you can return from the if()
, removing the else
block altogether.
public void DoSomethingWithWidgets(ICollection<Widget> widgets)
{
if (widgets.Count == 0)
{
HandleEmptyCollection();
return;
}
foreach (widget in widgets)
{
ProcessWidget(widget);
}
}
Or instead put the code in their own classes altogether, and let a class determine for itself whether it applies to its inputs. You could implement that like this:
public interface IVisitor
{
bool CanVisit(ICollection<Widget> widgets);
void Visit(ICollection<Widget> widgets);
}
public class EmptyCollectionVisitor : IVisitor
{
public bool CanVisit(ICollection<Widget> widgets)
{
return widgets.Count == 0;
}
public void Visit(ICollection<Widget> widgets)
{
// Handle empty collection
}
}
public class NotEmptyCollectionVisitor : IVisitor
{
public bool CanVisit(ICollection<Widget> widgets)
{
return widgets.Count > 0;
}
public void Visit(ICollection<Widget> widgets)
{
foreach (var widget in widgets)
{
// Process widget
}
}
}
Then you let all visitors visit the collection if they can, and you're done. With the added benefit that the classes themselves are better testable and more reusable.
You then utilize it by iterating over the registered visitors:
var yourInputCollection = { either a list that is empty or not };
IVisitor[] collectionVisitors = new[] {
new EmptyCollectionVisitor(),
new NotEmptyCollectionVisitor()
};
foreach (var visitor in collectionVisitors)
{
if (visitor.CanVisit(yourInputCollection))
{
visitor.Visit(yourInputCollection);
}
}
Yes, this may seem like overkill, but abusing syntax to fit as much code as possible on as little horizontal space as possible ranks even lower in elegance on my scale.