Java – Boolean return of set.add() in if conditional

clean codecoding-stylejava

The add operator of the set class returns a boolean which is true if the element (which is to be added) wasn't already there, and false otherwise. Is writing

if (set.add(entry)) {
    //do some more stuff
}

considered good style in terms of writing clean code?
I am wondering since you do two things at once. 1) adding the element and 2) checking whether the element existed.

Best Answer

Yes, it is.

The usual point of having an operation return a Boolean value is that you can use it to make decisions, i.e. within an if construct. The only other way you could realize this potential would be to store the return value in a variable and then immediately reuse it in an if, which is just silly and certainly not in any way preferable to writing if(operation()) { ... }. So just go ahead and do that, we won't judge you (for that).