Let’s say we have these checkboxes:
- FooCheckBox
- BarCheckBox
- BazCheckBox
And these methods:
- Foo
- Bar
- Baz
I want to call each method only if the correponding checkbox is checked. The code might look like this:
void DoWork()
{
if (FooCheckBox.Checked)
{
Foo();
Console.WriteLine("Foo was called");
}
if (BarCheckBox.Checked)
{
Bar();
Console.WriteLine("Bar was called");
}
if (BazCheckBox.Checked)
{
Baz();
Console.WriteLine("Baz was called");
}
}
Now consider that instead of 3 checkboxes and 3 methods you have a lot more. How would you rewrite the code above to make it more DRY?
I would say for the case you presented, leave it as is; you don’t want to over-abstract without having a good reason, as it can make a code base less maintainable. Of course context matters though, and it’s ultimately a judgement call.
That said, here’s how I would approach this. Create a collection where each item contains both the control and the action delegate. Then loop through and perform the logic on each item.
Or (possibly?) better using Linq: