我有一些功能取决于许多条件。条件语句中的所有变量都是布尔变量,代码如下,我不喜欢它:
if (userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
有没有办法让它更容易理解?
答案 0 :(得分:2)
这就像你用JavaScript一样简洁。我想如果你真的想,你可以创建变量来存储你的二元期权:
var multiMarketOneSelected = userHasMoreThanOneMarket && isOnlyMarketSelected;
var singleMarketMultiAgency = !userHasMoreThanOneMarket && userHasMoreThanOneAgency;
if (multiMarketOneSelected || singleMarketMultiAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
虽然我不知道你是否从中获得了很多可读性。
答案 1 :(得分:1)
你的代码看起来很好,但是如果你不喜欢它你可以做这样的事情(请注意,这里唯一的改进是风格,如果你更喜欢它):
function check(){
return {
valid: userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency,
case: [
isOnlyAgencySelected,
noAgencySelected && isOnlyMarketSelected
]
};
}
var conditions = check();
if (conditions.valid) {
if (conditions.case[0]) {
//do case 1
} else if (conditions.case[1]) {
//do case 2
}
}
答案 2 :(得分:1)
我会尝试使代码更具可读性:
!userHasMoreThanOneMarket
变为userHasOneMarket
isOnlyMarketSelected
对我来说听起来多余。你正在外面的if子句和内部再检查它。return;
语句以消除if-conditions。我希望这会有所帮助。