Reputation:
I'm in trouble trying to reduce this section of code of my function:
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;
}
How could I simplify/reduce the amount of source code for these IF clauses?
Upvotes: 2
Views: 55
Reputation: 3512
Your if clauses can be rewritten to:
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;
}
}
}
}
And then to:
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";
}
Another possible syntax, depending on the programming language (e.g. 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";
}
Which could then be written into a single line:
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";
}
Some languages support such kind of syntax (e.g. 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";
Upvotes: 1
Reputation: 1418
You have 3 if statements that return the same true value. You can use the ||
orelse operator with brackets to combine these statements into one line like this
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;
}
hope this helps
EDIT - Are the two later if statements nested inside the first one? hard to tell if was just a formatting issue.. if they are nested then you want the &&
andalso operator to combine the first if statement with each and then orelse to combine the two like this:
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;
}
Upvotes: 0