我在尝试减少我的函数的这段代码时遇到了麻烦:
checkData(day, month, year, area)
{
if(area == "year" && year == this.year)
return true;
if(area == "month" && month == this.div && year == this.year)
return true;
if(area == "day" && day == this.day && month == this.div && year == this.year)
return true;
return false;
}
如何简化/减少这些IF子句的源代码量?
答案 0 :(得分:2)
您的if子句可以重写为:
checkData(day, month, year, area)
{
if(year == this.year) {
if(area == "year") return true;
if(month == this.div) {
if(area == "month") return true;
if(day == this.day) {
if(area == "day") return true;
return false;
}
}
}
}
然后执行以下操作:
checkData(day, month, year, area)
{
if(year != this.year) return false;
if(area == "year") return true;
if(month != this.div) return false;
if(area == "month") return true;
if(day != this.day) return false;
return area == "day";
}
另一种可能的语法,具体取决于编程语言(例如C ++):
checkData(day, month, year, area)
{
return
year != this.year ? false :
area == "year" ? true :
month != this.div ? false :
area == "month" ? true :
day != this.day ? false :
area == "day";
}
然后可以将其写成一行:
checkData(day, month, year, area)
{
return year != this.year ? false : area == "year" ? true : month != this.div ? false : area == "month" ? true : day != this.day ? false : area == "day";
}
某些语言支持这种语法(例如C#):
checkData(day, month, year, area) => year != this.year ? false : area == "year" ? true : month != this.div ? false : area == "month" ? true : day != this.day ? false : area == "day";
答案 1 :(得分:1)
您有3个if语句返回相同的真实值。您可以使用带有括号的||
orelse运算符将这些语句组合成这样的一行
checkData(day, month, year, area){
if ((area == "year" && year == this.year) || (area == "month" && month == this.div && year == this.year)|| (area == "day" && day == this.day && month == this.div && year == this.year))
return true;
return false;
}
希望这会有所帮助
EDIT -后两个if语句是否嵌套在第一个中?很难分辨出是否仅仅是格式问题。如果它们是嵌套的,那么您想让&&
andalso运算符将每个if语句与第一个if语句组合在一起,然后将orelse像这样将两者组合在一起:
checkData(day, month, year, area){
if (area == "year" && year == this.year) && (area == "month" && month == this.div && year == this.year)
|| (area == "year" && year == this.year) && (area == "day" && day == this.day && month == this.div && year == this.year)
return true;
return false;
}