How to make this code more DRY?
c#, dry
Solution
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.
var items = new KeyValuePair<CheckBox, Action>[] {
new KeyValuePair<CheckBox,Action>(FooCheckBox, Foo),
new KeyValuePair<CheckBox,Action>(BarCheckBox, Bar),
new KeyValuePair<CheckBox,Action>(BazCheckBox, Baz)
};
foreach (var item in items)
{
if (item.Key.Checked)
{
item.Value.Invoke();
Console.WriteLine("Invoked " + item.Value.Method.Name);
}
}
Or (possibly?) better using Linq:
items.Where(item => item.Key.Checked).ToList().ForEach(item => new {
item.Value.Invoke();
Console.WriteLine("Invoked " + item.Value.Method.Name);
});
Problem
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?