samedi 5 mars 2016

Regex if-statements mixed with switch statements

I am working with some Java code that is comprised of a switch statement comparing strings. There are about 5 cases before learning that more needed to be added.

In fact I would need to add 64 more cases (4 groups of 16 similarly spelled values) and due to the nature of the strings was hoping to use regex to not need so many statements. For example, the first group of possible values is "Section ## Stuff", the second group "Section ## Stuff XYZ", and so on; where the ## is any number between 1 and 16.

To clarify, instead of adding a case for each string, I wanted to regex out the type, and then call the appropriate function, etc.

While this is all working correctly, I am worried that it will be hard for another developer to make sense of what is happening, as I have essentially combined regex if-statements and switch statements. I also cannot stand having very large switch statement lists.

What is the better option (readability vs eloquence, etc.), and is it possible to somehow use regex with my switch statement? Also, I don't think there would be any significant performance hit, but if there is, it would be nice to know. :)
Code below is an example as I cannot provide the real code.

What I want to do:

    if (str.matches("Section ([1-9]|1[0-6]) Stuff") {
        //do something with the number provided in string
    } else if (str.matches("Section ([1-9]|1[0-6]) Stuff 2") {
        //do something else with the number provided in the string
    } else {
        switch (str) {
        case PARAM_VALUE_1:
            doSomething1();
            break;
        case PARAM_VALUE_2:
            doSomething2();
            break;
        ...
        ...
        default:
            break;
        }
    }

  • OR -

    switch (str) {
        case PARAM_VALUE_1:
            doSomething1();
            break;
        case PARAM_VALUE_2:
            doSomething2();
            break;
        ...
        ...
        case "Section 1 Stuff":
            //do something for section 1
            break;
        case "Section 2 Stuff":
            //do something for section 2
            break;
        ...
        ... (64 cases later)
        default:
            break;
        }
    }
    
    

Note: I cannot redesign the way the string comes in; it comes from another subsystem and it is what it is.

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire