Boolean multireturn refactoring - java

What do you think will be the best way to refactor this kind of boolean method?
if (someService.isTrue(importantArg)) {
return true;
} else if (someService.isSomeTrue(anotherArg)) {
return isAnotherCondition(entry);
} else {
return super.thisMethod();
}

This is a minor refactoring, but you can remove the elses as you can't reach that code if the previous condition was true (if it was true, it would have returned a value and exited the method)
if (someService.isTrue(importantArg)) {
return true;
}
if (someService.isSomeTrue(anotherArg)) {
return isAnotherCondition(entry);
}
return super.thisMethod();

return someService.isTrue(importantArg) || (someService.isSomeTrue(anotherArg)
&& isAnotherCondition(entry)) || super.thisMethod();

Related

Why do I get a missing return statement error although there is a return statement in each of my if and if else blocks?

What I am trying to do here out of flower1 and flower2, one is even and one is odd then return true.
If both are even, return false.
If both are odd, return false.
When my code is:
public class OppositesAttract {
public static boolean isLove(final int flower1, final int flower2) {
if(flower1%2==0 && flower2%2==0){
return false;
}else
if(flower1%2!=0 && flower2%2!=0){
return false;
} else
if(flower1%2==0 || flower2%2==0){
return true;
}
}
}
I get a "missing return statement" error.
So I added:
public class OppositesAttract {
public static boolean isLove(final int flower1, final int flower2) {
if(flower1%2==0 && flower2%2==0){
return false;
}else
if(flower1%2!=0 && flower2%2!=0){
return false;
} else
if(flower1%2==0 || flower2%2==0){
return true;
}else{
return true;
}
}
}
Now, the code works but I do not understand why I have to add the additional return statement.
The compiler doesn't know the first 3 terms cover all situations.
if(flower1%2==0 && flower2%2==0){
return false;
} else if(flower1%2!=0 && flower2%2!=0){
return false;
} else if(flower1%2==0 || flower2%2==0){
return true;
}
to you this reads as: all options are covered. but the compiler just sees:
if (somethingThatMayBeTrue) {
} else if (somethingElseThatMayBeTrue) {
} else if (aThirdThingThatMayBeTrue) {
} .... and what if none of them are?
You may know that the last else if should always be true (since you know they are not both uneven) but the compiler doesn't generally try to understand your code.
in your case, the last clause (aThirdThingThatMayBeTrue, flower1%2==0 || flower2%2==0) is actually (somethingThatIsAlwaysTrueIfPreviousTermsAreFalse).
so you can treat it as such:
if(flower1%2==0 && flower2%2==0){
return false;
} else if(flower1%2!=0 && flower2%2!=0){
return false;
} else {
return true;
}

writing a java method that returns a boolean from a search

I have written a method that searches a tree to test if any integers are negative.
But I am struggling to get the right Boolean value returned. Any pointers as to where I am going wrong?
What I want to achieve is that as soon as the condition statement is met a false is returned but unfortunately my code is always returning a true
static boolean allE(Tree<Integer> x) {
if (x.isEmpty()) return true;
else {
if (x.getValue()%2 != 0) return false;
}
allE(x.getLeft());
allE(x.getRight());
return true;
}
When you recurse on allE you need to consider the result of that recursion. Easiest fix I see, change
allE(x.getLeft());
allE(x.getRight());
return true;
to
return allE(x.getLeft()) && allE(x.getRight());
Although, I think it makes more sense to write the algorithm such that you recurse on even explicitly. And allE saves three letters compared to allEven (please use meaningful names for methods and variables). Something like,
static boolean allEven(Tree<Integer> node) {
if (node.isEmpty()) {
return true;
} else if (node.getValue() % 2 == 0) {
return allEven(node.getLeft()) && allEven(node.getRight());
}
return false;
}
You're not using the results of your recursive tests properly.
It should be:
if (x.isEmpty()) {
return true;
}
boolean thisNodeEven = x.getValue() % 2 == 0;
return thisNodeEven && allE(x.getLeft()) && allE(x.getRight());
I suppose you need to evaluate the return-value of the recursive calls:
static boolean allE(Tree<Integer> x)
{
if (x.isEmpty())
return true;
else {
if (x.getValue()%2 != 0) return false;
}
if(!allE(x.getLeft()) || !allE(x.getRight()))
return false;
return true;
}

SonarLint "Replace this if-then-else statement by a single return statement"

Im not being able to fix this code smell:
public static boolean esStringVacio(final Object valor) {
if (valor == null) {
return true;
}
String valorTrim = valor.toString().trim();
if ((valorTrim).equals("")) {
return true;
}
if ((valorTrim).equals("null")) {
return true;
}
return false;
}
Tried like so but code smell persist:
if (valor == null || valor.toString().trim().equals("") || valor.toString().trim().equals("null")) {
return true;
} else {
return false;
}
You can shorten it to:
return (valor == null || valor.toString().trim().equals("") || valor.toString().trim().equals("null"));
Edit :
You can shorten even more to:
return ((String.valueOf(valor).trim().equals("null")) || (StringUtils.isBlank(valor)) ;
Thanks to Ernest for suggesting this.
You can combine the last 3 returns into a single OR, and it'd still be reliable / readable.
public static boolean esStringVacio(final Object valor) {
if (valor == null) {
return true;
}
String valorTrim = valor.toString().trim();
return valorTrim.equals("") || valorTrim.equals("null");
}

Is what the compile issue telling me wrong?

the below is the code I made for a codingbat problem. I think my code looks fine. the problem is below:
When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return true if the party with the given values is successful, or false otherwise.
cigarParty(30, false) → false
cigarParty(50, false) → true
cigarParty(70, true) → true
it keeps saying compile issue, "(" expected at line 6. Am i doing something wrong that I can't see?
public boolean cigarParty(int cigars, boolean isWeekend) {
if (cigars>=40 || cigars <= 60 && isWeekend){
return true;
} if else(cigars<40){
return false;
} else {
return false;
}
}
if else is wrong you should correct it to else if. This is the correct code :
public boolean cigarParty(int cigars, boolean isWeekend) {
if (cigars>=40 || cigars <= 60 && isWeekend){
return true;
}else if(cigars<40){
return false;
} else {
return false;
}
}
There is no if else, you have to use else if.
public boolean cigarParty(int cigars, boolean isWeekend) {
if (cigars>=40 || cigars <= 60 && isWeekend){
return true;
}else if(cigars<40){
return false;
} else {
return false;
}
}

Booleans and returns

public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
return true;
}
else {
return false;
}
}
Can the code above be written without the else statement and just have return false; after the if statement and still have the same result? If so, why? This is what I mean
public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
return true;
}
return false;
}
You should just write
public boolean percentDepreciatedOutOfRange() {
return percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX);
}
which is more readable. Avoid statements like
If (xxx) { return true; }
else { return false; }
because the if just adds noise around the expression.
The reason why this is legal is that the boolean type is the same in evaluating the if expression and in the return type of the method.
Because return actually exits the function (method).
In the case the if is not entered the rest of the code will execute normally.
Since you have boolean returns, having return false at the end of the function, means everything up to the end failed.
You could even rewrite it to:
public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN) {
return true;
}
if (percentDepreciated > DEPRECIATION_MAX) {
return true;
}
return false;
}
To clearly state the tests in the method.
Another way I like:
Defining return variable as 1st statement with default value.
Change the variable in method in various biz logic
Return the variable value (Single return statement)
public boolean percentDepreciatedOutOfRange() {
boolean status = false;
status = percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX;
return status;
}

Categories