Nested switch statements

Occasionally, I find myself looking at code with nested switch statements, which need to be modified. For example, the following nested switch statements in MATLAB look at different particle types and charges:

switch(particleType)
    case 'lepton'
        switch(charge)
            case 'negative'
               name = 'electron';
            case 'positive'
               name = 'positron';
            otherwise
               assert('Unknown charge');
        end
    case 'baryon'
        switch(charge)
            case 'negative'
                name = 'anti-proton';
            case 'neutral'
                name = 'neutron';
            case 'positive'
                name = 'proton';
            otherwise
                assert('Unknown charge');
        end
    otherwise
        assert('Unknown particle type');
end

A nice way to refactor this is to combine the cases of the nested switch statements:

matchStr = [particleType '_' charge];

switch(matchStr)
    case 'lepton_negative'
        name = 'electron';
    case 'lepton_positive'
        name = 'positron';
    case 'baryon_negative'
        name = 'anti-proton';
    case 'baryon_neutral'
        name = 'neutron';
    case 'baryon_positive'
        name = 'proton';
    otherwise
        assert('Unknown particle type and charge');
end

This makes the code cleaner and easier to modify for future use.

Leave a Reply

Your email address will not be published. Required fields are marked *