Clean Code – How to Reduce a Switch in a Switch Statement

clean codecoding-styledesign-patternsswitch statement

So I'm making a method to create a salutation line based on two people from a database.

There are four parameters: the two names (name1 and name2) and the two genders (gender and gender2).

For every gender combination, I have a kind of different output.

For example: if gender 1 is M (man) and gender 2 is also M, the output should be something like:

Dear Sir name1 and Sir name2,

At this time, my switch looks like this:

switch(gender1){
    case 'M':
        switch(gender2){
            case 'M': printf("Dear Sir %s and Sir %s", name1, name2); break;
            case 'W': printf("Dear Sir %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case 'W':
        switch(gender2){
            case 'M': printf("Dear Madame %s and Sir %s", name1, name2); break
            case 'W': printf("Dear Madame %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case ...etc.
}

Note that I have multiple gender options, like 'R' for "Dear Relation" and some more that I do not have the time to translate.

How can I reduce this double switch statement?

Putting the second switch in a method is not an option because there is also a case where both of the names are the same and then the output should be combined like: "Dear Sir and Madame name1,"

Best Answer

Add the title to the parameters of the printf:

char* title1;
switch(gender1){
    case 'M':
        title1 = "Sir";
        break;
    case 'W':
       title1 = "Madam";
        break;
    case ...etc.
}
char* title2;
switch(gender2){
    case 'M':
        title2 = "Sir";
        break;
    case 'W':
       title2 = "Madam";
        break;
    case ...etc.
}
printf("Dear %s %s and %s %s", title1, name1, title2, name2);

you can extract the switch to its own function for re-usability and compactness.