2

I'm trying to make a Java method close() which closes object if it is open, and which returns true if the action succeeded.

public boolean close() {
        if (open) {
            open = false;
            return true;
        } else {
            return false;
        }
    }

I'm trying to find a way to write this down with less code. What I came up with is the following.

public boolean close() {
        return (open && (open = false));
    }

Eclipse doesn't give any errors when I write this down. The left hand side of the evaluation checks if open is true, and if so, the right hand side should set open to false and return true as well.

I've tested the code, and open does get set to false, but it doesn't return true. Is there a way to make this work?

HYBR1D
  • 464
  • 2
  • 6
  • 19

6 Answers6

3

Perhaps something like:

public boolean close () {
    return open != (open = false);
}

but if I was reviewing this code I would reject it as unclear.

I would probably do it using maximal clarity as:

public boolean close () {
    boolean wasOpen = open;
    open = false;
    return wasOpen;
}

and let the compiler optimise.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
2

You could do it without conditional execution by preparing the return value before the assignment of false, like this:

boolean wasOpen = open;
open = false;
return wasOpen;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    I promise I didn't see this before I edited mine. – OldCurmudgeon Nov 27 '17 at 15:53
  • @OldCurmudgeon I have no doubt about that :-) This is so simple that it's easy to see how multiple people could come up with the same solution, down to the naming of variables. I like your first solution, too (as you can probably see from my comment). – Sergey Kalinichenko Nov 27 '17 at 15:55
  • Second place for shortness but first place for clarity. I would definitely use this. – Luke Nov 27 '17 at 15:57
1
return open ? !(open = false) : open;

or

return open ? !(open = false) : false;

Though, I don't like the idea of making the first snippet shorter. You are killing readability where it's already absent.

Personally, I would go with the original method introducing a local variable wasOpen as @dasblinkenlight suggested.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

Not really, the assignment is evaluated prior to the rest of the expression, so what you're essentially saying is:

true && false

Also known as false

Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
0

You can try this

public boolean close() 
{     return !open = (open == true) ? false: true; }
0

Your expression will evaluated as the following true && false,so the result is false

public boolean close() {
    if(!open) return open;
    open=false;
    return true;
}
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39