Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do i eliminate Switch statement?

I have a tab control which has 3 tab pages. Below this tab control on same form/view, i have 3 images controls.

Based on SelectedIndex of tab, i need to change opacity of below 3 images.

As of now i have something like this in SelectionChanged event of Tab control:

switch (Tab.SelectedIndex)
{
     case 0:
         img1.Opacity= 1;
         img2.Opacity = 0.5;
         img3.Opacity  = 0.5;
         break;
     case 1:
         img1.Opacity = 0.5;
         img2.Opacity = 1;
         img3.Opacity  = 0.5;
         break;
     case 2:
         img1.Opacity = 0.5;
         img2.Opacity = 0.5;
         img3.Opacity = 1;
         break;
}

How do i remove this switch statement? Which design pattern shall i use here ?

like image 418
NoobDeveloper Avatar asked Oct 21 '22 00:10

NoobDeveloper


2 Answers

I think you can handle this in your xaml itself by using Triggers.

Also if you want to have this unit testable, you should use MVVM pattern where you will define properties for SelectedIndex, Opacities in your ViewModel and bind them to xaml

like image 135
Nitin Avatar answered Oct 23 '22 20:10

Nitin


You can use the State design pattern explained for instace here. You will define few states and then by condition decide which of them should be used in the moment.

Example:

abstract class State
{
    abstract vod Apply(Form context);
}

class StateOne : State
{
    override void Apply(Form context)
    {
        img1.Opacity= 1;
        img2.Opacity = 0.5;
        img3.Opacity  = 0.5;
    }
}

You can also combine it with the Factory method design pattern that would decide which state to use.

static class StateFactory
{
    static State GetState(condition)
    {
        if(condition == something)
            return new StateOne();
        else ...
    }
}

This will not remove switch statements from your code, but it will at least be in a reasonable place doing reasonable thing.

Usage:

StateFactory.GetState(condition).Apply(this);
like image 26
Ondrej Janacek Avatar answered Oct 23 '22 19:10

Ondrej Janacek