Home > database >  I want to eliminate all of these case statements (too messy)
I want to eliminate all of these case statements (too messy)

Time:07-08

I am writing a test program which returns a string "P3-PASS" or "P3-FAIL. In all there are 12 possible tests, P3 to P14 ("P3-FAIL" to "P14-PASS").

I have a button "All_Tests" which calls each test 1 by 1, and the associated button changes colour based on the result.

Ideally I want to do something like PageNum.Background = Brushes.Red, but I can't do this because I can't use a string to access the button. Hence the case statements below. Is there a way to simplify this, because it looks awful. OR is there a way to access the relevant button using a string, or similar. Many Thanks

int PageNum = Int32.Parse(PageTstName);

switch (PageNum)
{
    case 3:
        if (TstResult == "PASS")
        {
            Pg3.Background = Brushes.SeaGreen;
            Pg3.Foreground = Brushes.White;
        }
        else // TstResult is "FAIL"
        {
            Pg3.Background = Brushes.Red;
            Pg3.Foreground = Brushes.White;
        }
        break;

    case 4:
        if (TstResult == "PASS")
        {
            Pg4.Background = Brushes.SeaGreen;
            Pg4.Foreground = Brushes.White;
        }
        else // TstResult is "FAIL"
        {
            Pg4.Background = Brushes.Red;
            Pg4.Foreground = Brushes.White;
        }
        break;

    case 5: .....etc

CodePudding user response:

You can create a dictionary that maps the numbers to the controls, e.g.

var controlsByPageNum = new Dictionary<int, Button>() 
{
  { 3, Pg3 },
  { 4, Pg4 },
  { 5, Pg5 },
  // ...
}

When receiving the test results, you can get the control like this:

int PageNum = Int32.Parse(PageTstName);
var btn = controlsByPageNum[PageNum];
if (TstResult == "PASS")
{
  btn.Background = Brushes.SeaGreen;
  btn.Foreground = Brushes.White;
}
else // TstResult is "FAIL"
{
  btn.Background = Brushes.Red;
  btn.Foreground = Brushes.White;
}

CodePudding user response:

Create a method to apply your colors:

private static void ApplyColors(Control control, Brush background, Brush foreground)
{
    control.Background = background;
    control.Foreground = foreground;
}

And a dictionary to map each case:

private readonly Dictionary<string, Action> dict = 
    new Dictionary<string, Action>();

Now, in your constructor, fill the dictionary:

dict[$"3~PASS"] = () => ApplyColors(Pg3, Brushes.SeaGreen, Brushes.White);
dict[$"3~FAIL"] = () => ApplyColors(Pg3, Brushes.Red, Brushes.White);
dict[$"4~PASS"] = () => ApplyColors(Pg4, Brushes.SeaGreen, Brushes.White);
dict[$"4~FAIL"] = () => ApplyColors(Pg4, Brushes.Red, Brushes.White);

Here, for each page and result, you define the action to execute. With this, now you can manage your current switch in this way:

var key = $"{PageTstName}~{TstResult}";
if (dict.TryGetValue(key, out Action action))
{
    action();
}
else
{
    // A non mapped case...
}
  • Related