I am learning about conditionals and want to know if this is a bad convention for similar situations. Should I define isOdd() without using isEven()?
static boolean isEven(int i) {
return i % 2 == 0;
}
static boolean isOdd(int i) {
return !isEven(i);
}
No, that's absolutely fine, and code reuse is positively encouraged - if you actually need both methods, of course. Is it really too hard for the caller to use !isEven(...)
? Sometimes it can be worth it for the sake of caller readability, but I'd encourage careful consideration first.
However, what I would discourage is the approach of isEven
using an if
statement where the body just returns true or false. That can always be replaced by just returning the condition:
static boolean isEven(int i) {
return i % 2 == 0;
}