更好地设计子分支 if 语句子条件

better design for sub-branching if statement sub conditions

我正在尝试重构具有多个子条件的 if 语句。从我目前的尝试来看,我要么必须将条件写两次,要么将预期的结束函数写两次。我想要一种更简洁的方法。

这是我写的初始代码:

   if((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')){ // cipher uppercase letters
        bool uppercase = true;
        if (s[i] >= 'a' && s[i] <= 'z') { // cipher lowercase letters
            bool uppercase = false;
        }
        printf("%c", cipher_letter(s[i], true, k));
    }
    else { // do nothing on non-alphabet letters
        printf("%c", s[i]);
    }

我现在找到的更简洁的方法是:

if(s[i] >= 'A' && s[i] <= 'Z') { // cipher uppercase letters
    printf("%c", cipher_letter(s[i], true, k));
}
else if (s[i] >= 'a' && s[i] <= 'z') { // cipher lowercase letters
    printf("%c", cipher_letter(s[i], false, k));
}
else { // do nothing on non-alphabet letters
    printf("%c", s[i]);
}

但我必须重复 cipher_letter 函数。

什么是更好的样式设置?

为了回答你关于条件的问题,引入两个局部变量来缓存你测试的两个部分的结果。

bool isUpper = s[i] >= 'A' && s[i] <= 'Z';
bool isLower = s[i] >= 'a' && s[i] <= 'z';

if (isUpper || isLower) {
    printf("%c", cipher_letter(s[i], isUpper, k));
}
else { // do nothing on non-alphabet letters
    printf("%c", s[i]);
}

额外的名称还使测试的目的更加清晰,有助于理解稍后阅读代码的其他人(这可能包括您)。

已更新:我将错误的布尔值传递给了 cipher_letter;感谢捕获。

为了更好的设计,可以简化为:

if (isalpha(s[i]))
    putchar(cipher_letter(s[i], isupper(s[i]), k));
else
    putchar(s[i]);

甚至:

putchar(isalpha(s[i]) ? cipher_letter(s[i], isupper(s[i]), k) : s[i]);

我更喜欢前者,因为它看起来更清晰。

在效率的情况下,isalpha and isupper calls are likely to be implemented via macros, that refer to lookup table数组如__ctype_b_loc(GCC,Clang)。