public boolean cigarParty(int cigars, boolean isWeekend) {
if (isWeekend == false) {
return cigars >= 40 && cigars <= 60 ? true : false;
}
if (cigars >= 40) {
return isWeekend ? true : false;
}
else {
return false;
}
}
Does anyone have any feedback on how I could be more efficient with ternary operators?
CodePudding user response:
As @codebod said, much of your code is redundant.
This is one way to solve it with ternary operators:
public boolean cigarParty(int cigars, boolean isWeekend) {
return (isWeekend) ? (cigars >= 40): (cigars >= 40 && cigars <= 60);
}
This is one way to solve it without ternary operators:
public boolean cigarParty(int cigars, boolean isWeekend) {
if (isWeekend){
return (cigars >= 40);
}else{
return (cigars >= 40 && cigars <= 60);
}
}
CodePudding user response:
These ternary operators can be removed entirely. Each of your return statements already evaluates to the required boolean result. Your statements as written with the ternary operators essentially say: if true return true, else return false
, which is redundant.
I think the most readable form that includes a ternary operator, if that's what's needed, is:
public boolean cigarParty(int cigars, boolean isWeekend) {
if (cigars < 40){
return false;
}
return isWeekend ? true : cigars <= 60;
}
This also eliminates the repeated comparison of cigars
with 40
.
CodePudding user response:
Converting to symbolic logic and applying de Morgan's laws I came up with this.
- if
cigars < 40
it will returnfalse
and short circuit the expression. - if either of the others is
true
it will returntrue
public static boolean cigarParty(int cigars, boolean isWeekend) {
return cigars >= 40 && (cigars <= 60 || isWeekend);
}