Alex Rivera | Logout

How to make this code more DRY?

Asked 2012-06-23T21:56:14.660
8

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?

Edit
Report

1 Answer

6

You could use a Dictionary to keep up with what actions refer to which checkboxes. Then you could do the following:

foreach(KeyValuePair<CheckBox, Action> kvp in Dict)
{
    if(kvp.Key.Checked)
        kvp.Value.Invoke();
}
answered 2012-06-23T22:02:23.273

Your Answer