Alternative for Switch within Switch

6

I'm making a decision structure that depends on more than one variable, but readability and maintenance using if or switch are bad.

What alternatives do I have for this case?

Example of% nested% nested:

switch (var1)
{
    case "A":
        switch (var2)
        {
            case 0:
                ...
                break;
            case 1:
                ...
                break;
            case 2:
                ...
                break;
        }
        break;
    case "B":
        switch (var2)
        {
            case 0:
                ...
                break;
            case 1:
                ...
                break;
            case 2:
                ...
                break;
        }
        break;
}

In the actual situation I'm doing a crawler style program that from a single form need to replicate the information by filling out similar forms on several other websites. In my form I have, for example, combo with dozens of professions, so I need the same profession that is chosen here to be mapped to the corresponding option of the other site.

The option that my combo is switch on one site is Engenheiro (a) , on another it is Engenheiro , on another it Engenheiro (outros) , on other it Engenheiro(a)/Arquiteto(a) .. .

So in the real case, the variables I use in Engenheiro/Arquiteto are the name of the site I'm mapping and the option selected in combo .

    
asked by anonymous 01.06.2016 / 00:58

2 answers

11

In fact the switch-case command is quite ugly and almost always dispensable

Instead of using this command or long strings from if-elseif-elseif ... , you can use dictionaries.

In your case, you would populate a dictionary of dictionaries, with the following semantics:

profissão -> site -> profissão naquele site

So, instead of making a long, confusing, ugly and hard-to-maintain imperative code like this:

switch (profissao_selecionada)
{
    case "Engenheiro(a)":
        switch (site_selecionado)
        {
            case "site A":
                profissao_no_outro_site = "Engenheiro/Arquiteto";
                break;
            case "site B":
                profissao_no_outro_site = "Engenheiro (outros)";
                break;
        }
        break;
    case "Astronauta":
        switch (site_selecionado)
        {
            case "site A":
                profissao_no_outro_site = "Cosmonauta";
                break;
            case "site B":
                profissao_no_outro_site = "Espaçonauta";
                break;
        }
        break;
}

You can associate profession and website in a more declarative way:

profissoes["Engenheiro(a)"]["site A"] = "Engenheiro/Arquiteto";
profissoes["Engenheiro(a)"]["site B"] = "Engenheiro (outros)";

profissoes["Astronauta"]["site A"] = "Cosmonauta";
profissoes["Astronauta"]["site B"] = "Espaçonauta";

And then on just a single line, without any switch-case , you check how the profession selected in the combo is defined on a particular site, :

profissao_no_outro_site = profissoes[profissao_selecionada][site_selecionado];

See that you can use the dictionary itself to populate the professions in the combo instead of replicating them in the combo and code to keep items in one place .

p>

Complete example

If you have any questions, see this complete functional example:

public partial class Form1 : Form
{
    Dictionary<String, Dictionary<String, String>> profissoes;

    public Form1()
    {
        InitializeComponent();

        var engenheiro = new Dictionary<String, String>();
        engenheiro["site A"] = "Engenheiro";
        engenheiro["site B"] = "Engenheiro (outros)";
        engenheiro["site C"] = "Engenheiro(a)/Arquiteto(a)";

        var astronauta = new Dictionary<String, String>();
        astronauta["site A"] = "Cosmonauta";
        astronauta["site B"] = "Espaçonauta";
        astronauta["site C"] = "Lunático";

        profissoes = new Dictionary<String, Dictionary<String, String>>();
        profissoes["Engenheiro(a)"] = engenheiro;
        profissoes["Astronauto(a)"] = astronauta;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (var profissao in profissoes)
            comboProfissoes.Items.Add(profissao.Key);
    }
    private void seleciona_Click(object sender, EventArgs e)
    {
        var profissaoSelecionada = (String)comboProfissoes.SelectedItem;
        var mensagem = "A profissão " + profissaoSelecionada 
            + " no site B é " + profissoes[profissaoSelecionada]["site B"];
        MessageBox.Show(mensagem);
    }
}

Whose "output" looks like this:

Storingcomplexcodeinthedictionary

WhatifineachblockcaseyouneededtorunsomelinesofcodeinsteadofsimplysettingavariablelikeIdidintheexampleabove?Thedictionaryisstillthesolution!

Intheexampleabove,weusethedictionarytostoretheprofession'scaptiononanothersite,butwecanuseittostoreanyobject,notjuststrings.Thatis,wecanaddblocksofcodeinthedictionarytoruninatimelymanner,dispensingtheswitch-caseinalmostanysituation.

SincethedictionarysupportsobjectsandalmosteverythinginC#isanobject,thereareseveralwaystostorecodeblocksinthedictionary:youcanstoreactions,
01.06.2016 / 20:07
1

Could leave default values

$valores = array(
    'carro' => array('item1' => 'pneu', 'item2' => 'pneu','item3' => 'pneu'),

    'moto' => array('item1' =>'gidao', 'item2' => 'pneu', 'item3' =>'quadro'),

    'caminhao' => array('item1' => 'volante', 'item2' =>'banco', 'item3' =>'porta'),

);

echo $ values [$ type] [$ item];

NOTE: I had not noticed that the question was for C #. As I said, just understand the idea.

    
01.06.2016 / 22:11