replace switch-case statements with table-driven approach

1.3k Views Asked by At

I'm refactoring some existing code which converts between A and B using switch-case statements, it looks like this:

<?php
function string2num($s)
{
    switch($s){
        case 'AB':
            return 1;
        case 'CD':
        case 'GH':
            return 2;
        case 'EF':
            return 3;
        ...
    }
}

function num2String($n)
{    
    switch($n){
        case 1:
            return 'AB';
        case 2:
            return array('CD', 'GH');
        ...
    }

}

And it has too many cases, which leads to large amounts of code, Now, I want to do this with table driven approach, but the problem is, when I build a table for string2num(): $table = array('AB' => 1, 'CD' => 2, 'GH' => 2, 'EF' => 3, ...);, I can't reuse the table in num2String()(I mean, array_flip($table), then use it) since the the duplicate values in $table will become only one key when flipping. I know I can do that with 2 tables, someone have a better solution?

1

There are 1 best solutions below

1
On BEST ANSWER

Create the table like this:

$table = array(
    'AB' => 1,
    'CD' => 2,
    'GH' => 2,
    'EF' => 3,
);

You can retrieve multiple keys using array_keys() function with optional search parameter, so

$keys = array_keys($table, 2);

will return

array('CD', 'GH');

Solution:

$table = array(
    'AB' => 1,
    'CD' => 2,
    'GH' => 2,
    'EF' => 3,
);

function string2num($table, $string) {
    if(isset($table[$string])) {
        return $table[$string]; 
    }
}

function num2String($table, $number) {    
    return array_keys($table, $number);

}