Why this if statement is not redudant in NetBeans 8.2 - java

I wrote a method in java class like this:
public boolean checkPlace() {
if (this.PlaceName.equals("Name Place"))
return true;
else return false;
}
I wonder why it is not redudant.
Could I write just return if statement?
Thanks in advance.

You could write:
public boolean checkPlace() {
return PlaceName.equals("Name Place");
}

It is redundant in general. Best practice would be to write
if (this.PlaceName.equals("Name Place")) {
return true;
}
return false;
Or if that is not just a dummy example
return this.PlaceName.equals("Name Place")
If you are more used to expression-like syntax from other languages, then Java does not allow you to write
return if (this.PlaceName.equals("Name Place")) true else false;
However it does support ternary expressions in which case you have to be sure you only have 2 branches and not more.
return this.PlaceName.equals("Name Place") ? true : false;

Related

How to return a break or Continue in a method is it possible?

When I'm using while loop I need to use many if blocks which are exactly same So I planed to put it in a method and reuse it where I want! but I had a problem I want to return Continue or break in some area of my if blocks so can I return Break or continue?
while (true){
move(a);
move(b);
}
public *** move(Parameter parameter){
if (statement){
return continue;
}
else{
return break;
}
}
You can return a boolean:
while (true){
if(move(a))
{
break;
}
else
{
continue;
}
if(move(b))
{
break;
}
else
{
continue;
}
}
public boolean move(Parameter parameter){
if (statement){
return false;
}
else{
return true;
}
}
I'm going to set aside the fact if we implemented what you want literally then move(b); would be unreachable. Presumably when you say continue you mean execute the next statement; not return to the start of the loop?
But sadly you can't achieve this in Java. In Java, you can only return a value, not an "instruction". (In C and C++ you can contrive this using a macro, although that messes up your debugger.)
However, if you adapt move to return a boolean which is say true if you want to break and false otherwise, then at the call site you could write
while (true){
if(move(a)){
break;
} else if (move(b)){
break;
}
}
or ace it with
while (true){
if (move(a) || move(b)){
break;
}
}
where I'm exploiting the short-circuiting nature of the operator ||.
Finally, if you want to submit this code to an obfuscation contest then use the simply beautiful but still comprehensible
while (!(move(a) || move(b)));
and if you want to guarantee that you win said contest, then swap the return rule of move round and use the utterly indecent
while (move(a) && move(b));
Make it super simple with a returning boolean
public boolean move(Parameter parameter){
return statement;
}
while (true){
if(!move(a)) break;
if(!move(b)) break;
}

how to use return keyword in a find operation in binary search tree

This is my method to find if a particular node is there in a binary tree.Here's my method and it works fine.
public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
return find(p.left,x);
}
else {
return find(p.right,x);
}
}
}
My question is if I don't insert return keyword inside else if(x<p.element){ and else { I get an error as missing return statement.
Say I have a binary tree consisting of elements 5,4,6,60,25,10 .
So if i am searching for 10 there's a time that
if(x==p.element){
return true;
is satisfied because of recursive calls.Then there's a return statement to be found.
If i am searching for an element that's not in tree eventually I would reach the statement
if(p==null){
return false ;
},there we find a return statement.
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?So what's wrong with not having return keyword in else if and else clauses.
Why do I have to have it there?
Why can't I do it as
`public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
find(p.left,x);
}
else {
find(p.right,x);
}
}
}`
The closest to the way you want your if-else if-else clause to behave is using the ? conditional expression:
public boolean find(BinaryNode p,int x)
{
if(p==null) {
return false ;
}
else {
return (x==p.element)?true:(x<p.element?find(p.left,x):find(p.right,x));
}
}
Other option is to store the value to be returned in a local variable and only return it at the end of your method:
public boolean find(BinaryNode p,int x)
{
boolean returnValue = false;
if(p!=null)
{
if(x==p.element){
returnValue = true;
}
else if(x<p.element){
returnValue = find(p.left,x);
}
else {
returnValue = find(p.right,x);
}
}
return returnValue;
}
And my favorite way, using short-circuit evaluation of logical expressions:
public boolean find(BinaryNode p,int x)
{
if(p==null) return false;
return x==p.element || (x<p.element && find(p.left,x)) || find(p.right,x);
}
Since Java's || and && operators won't evaluate their right part expression when the left part already determines their result. If x==p.element is true, then true will be returned without evaluation the rest of the line. If not, then (x<p.element && find(p.left,x)) will be evaluated following the same rule.
Note how find(p.left,x) won't be evaluated when x<p.element is false.
You need return statement because the find-function in the else if - else statement will return to the caller after its done, but the first-call function still have to return a value to the caller
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?
No compiler doesn't know about it. Compiler doesn't know what will be value of x and p at run-time.
Compiler simply checks for all the possibilities of the return statement and there must be exit point of the method.
You need to provide the logic to move either in right direction or left direction of the binary tree.
The last two else-if are not responsible to actually return the result of the find method its used just to move in the right direction of the tree. Ultimately final result of the the find method will come out by first two if-else clause.

Point of exit from a method in Java

In Eclipse, is there any way to find which return statement a method returned from without logging flags at every return statment?
For example:
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ABC)) {
return false;
}
ABC other = (ABC) obj;
if (var1 == null) {
if (other.var1 != null) {
return false;
}
} else if (!var1.equals(other.var1)) {
return false;
}
return true;
}
In this case, how do I find out at which point my equals method returned?
No, but a more understandable and debug friendly code can be with a boolean local variable that represents the result.
then you can see with debugger who assign it when and the return value before returned.
No. This is one reason that some people prefer single point of exit:
Why should a function have only one exit-point?
Note also the links in the first comment on that question.
Use breakpoints in debug mode.

Better way to structure/new keyword

Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently. I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation. Essentially it uses a for loop to provide a kind of structured goto. My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.
ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.
Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses
boolean valid = false;
// this loop never loops
for (;;)
{
if (!condition1)
break;
condition2.setup();
if (!condition2)
break;
condition3.setup();
if (!condition3)
break;
valid = true;
break;
}
if (valid) dosomething();
EDIT:
I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.
The restructured code looks like this.
boolean valid = false;
breakout:
{
if (!condition1)
break breakout;
condition2.setup();
if (!condition2)
break breakout;
condition3.setup();
if (!condition3)
break breakout;
valid = true;
}
if (valid) dosomething();
Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?
The loop is counter-intuitive and would be questioned at code review: "Why do you need a loop if you always break on the first iteration?"
Why not use this?
boolean valid = true;
if (!condition1)
valid = false;
else if (!condition2)
valid = false;
else if (!condition3)
valid = false;
if (valid) dosomething();
You may have heard of these things modern programming languages have, called functions ;)
One of the key reasons goto is no longer used is that we can now factor code out into separate functions, and call them instead.
One way to solve your problem would be to put the code in a separate function instead, and return instead of breaking from your pseudo-loop:
void safedosomething() {
if (!condition1)
return;
condition2.setup();
if (!condition2)
return;
condition3.setup();
if (!condition3)
return;
dosomething();
}
or write helper functions (such as bool checkcondition1() { condition1.setup(); return condition1; }) which set up and then test the conditions, and use a boolean flag:
bool valid = true;
if (!checkcondition1())
valid = false;
if (!checkcondition2())
valid = false;
if (!checkcondition3())
valid = false;
if (!checkcondition4())
valid = false;
if (valid) dosomething();
or a bit more concisely:
bool valid = true;
valid &&= checkcondition1();
valid &&= checkcondition2();
valid &&= checkcondition3();
valid &&= checkcondition4();
if (valid) dosomething();
or just
if (checkcondition1()
&& checkcondition2()
&& checkcondition3()
&& checkcondition4())
dosomething();
There are plenty of ways to express this, without counterintuitive loops-that-don't-loop.
The reason for this construct is because goto is a dirty word in programming. But lets face it, you are effectively using the loop construct to do the same thing. My opinion on this is either be honest and use the goto or refactor the code.
I don't think it's the most readable way of doing it. Chained if-else if looks much better. But if you want to stick with it and don't want to be so close to an infinite loop, you could do something like this:
do
{
if (...)
break;
...
} while (false);
C++ only, unfortunately:
if ( condition1
&& (condition2.setup(), condition2)
&& (condition3.setup(), condition3) )
{
dosomething();
}
For something java compatible (but I'm still writing C++!) I would fall back to something along the lines of this. (Obviously, some context may need to be passed into CheckConditions().)
bool CheckConditions()
{
if (!condition1)
return false;
condition2.setup();
if (!condition2)
return false;
condition3.setup();
if (!condition3)
return false;
return true;
}
//...
if (CheckConditions())
{
dosomething();
}
//...
You seem concerned that evaluating condition 2 requires some setup, and you don't know where to put it. Refactor that into a separate boolean method and then use that the way almost everybody here has described. For example:
if (checkCondition1() && checkCondition2(someInput) && checkCondition3()) {
doSomething();
}
and..
private boolean checkCondition2(Object someInput) {
//setup condition 2
return condition2;
}
I think the problem with
if (condition1 && condition2 && ...)
was simply that it could become hard to read and edit if there are lots of conditions, although you could always write it like this:
if ( condition1 &&
condition2 &&
condition3 ... )
doStuff();
How about you turn the loop into a function:
bool all()
{
if (!condition1) return false;
if (!condition2) return false;
if (!condition3) return false;
....
return true;
}
Here's sort of compromise, if you want to keep the indentation as it is:
boolean valid = true; // optimistic start
if (!valid || !condition1)
valid = false;
if (!valid || !condition2)
valid = false;
if (!valid || !condition3)
valid = false;
if (valid)
doSomething();
The !valid in the first if statement is superflucious but doesn't harm, could be kept for readability. else/if is more elegant, to my opinion, but that's just an opinion.
But I really wouldn't (ab-)use the for loop and I never ever would find a cheap way to implement a pseudo-goto. There's always a better solution.
I'm not sure why you need a loop if there is a break statement at the end of the loop. Arent you just iterating once, no matter the situation?
Anyway, you'll usually find two differing opinions concerning this on SO, one being that break statements shouldn't be used at all, and one being that it depends on the situation.
I tend to fall in with the latter group, but the way that your loop works uses superfluous break statements. I'd much rather structure such a loop like this:
bool valid = true;
for(... ; .... && valid == true ; ....)
{
if (!condition1)
valid = false;
if (!condition2)
valid = false;
if (!condition3)
valid = false;
}
This allows a loop exit that I think is more elegant.
Having such a long if statement is most likely bad coding.
It makes it very hard to test, and is most likely a code smell.
If possible you should refactor to take advantage of polymorphism.
How about relocating the setup to the operator bool on the Condition class? This makes it far more readable and hides the mechanics.
class Condition
{
bool _isSet;
public:
Condition() : _isSet(false) {
}
void setup() {
_isSet = true;
}
operator bool () {
if (!_isSet) {
setup();
}
return rand() & 1;
}
};
void doSomething()
{
}
int _tmain(int argc, _TCHAR* argv[])
{
Condition cond1, cond2, cond3;
if (cond1 && cond2 && cond3) {
doSomething();
}
return 0;
}
You can take that code out to a separate function and use multiple return statements. You will likely need to refactor the long list of if statements into a separate function anyway.
bool isValid()
{
if (!condition1)
return false;
condition2.setup();
if (!condition2)
return false;
condition3.setup();
if (!condition3)
return false;
return true;
}
Then you could use it in your code:
if (isValid()) dosomething();

Cleanest way to toggle a boolean variable in Java?

Is there a better way to negate a boolean in Java than a simple if-else?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
theBoolean = !theBoolean;
theBoolean ^= true;
Fewer keystrokes if your variable is longer than four letters
Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.
There are several
The "obvious" way (for most people)
theBoolean = !theBoolean;
The "shortest" way (most of the time)
theBoolean ^= true;
The "most visual" way (most uncertainly)
theBoolean = theBoolean ? false : true;
Extra: Toggle and use in a method call
theMethod( theBoolean ^= true );
Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.
This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)
Boolean.valueOf(aBool).equals(false)
or alternatively:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
If you use Boolean NULL values and consider them false, try this:
static public boolean toggle(Boolean aBoolean) {
if (aBoolean == null) return true;
else return !aBoolean;
}
If you are not handing Boolean NULL values, try this:
static public boolean toggle(boolean aBoolean) {
return !aBoolean;
}
These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.
Usage
boolean bTrue = true
boolean bFalse = false
boolean bNull = null
toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true
Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:
Boolean b = false
b = b.toggle() // == true
The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang
BooleanUtils.negate(theBoolean)
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;
If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.
public class Util {
public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }
}
then just create a Util object
Util u = new Util();
and have something for the return System.out.println( u.flip(bool) );
If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)
Before:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
After:
boolean result = isresult();
result ^= true;

Categories