Problem
I have this very simple method:
private boolean isTheParticipantTalking(ParticipantID participantId){
if(mCurrentParticipant != null) {
return participantId.equals(mCurrentParticipant.getId());
}
return false; // no one is talking
}
I receive a warning stating that I can simplify the code in the following manner:
private boolean isTheParticipantTalking(ParticipantID participantId){
return mCurrentParticipant != null && participantId.equals(mCurrentParticipant.getId());
}
In your opinion, is this change desirable? I understand that we go from 4 lines of code to just 1, but I find my way more understandable in one blick.
Solution
I prefer your method, because it’s a lot clearer. But I would turn the if around (first check the input, then the normal action):
private boolean isTheParticipantTalking(ParticipantID participantId){
if(mCurrentParticipant == null) {
return false; // no one is talking
}
return participantId.equals(mCurrentParticipant.getId());
}
Another question is if this is actually the best approach.
Is a non-existing participant talking?
That question really doesn’t make so much sense.
You could use Objects.requireNonNull
which seems to have been written exactly for cases like this, or throw your own NullPointerException if you want to.
It’s hard to give an objective answer, but for me this is the winner. Concise and readable.
private boolean isTheParticipantTalking(ParticipantID participantId) {
return
mCurrentParticipant != null &&
participantId.equals(mCurrentParticipant.getId());
}
You must understand that return
means true
for compiler while it concider that this expression performs, so in that case it might be true
only if mCurrentParticipant != null
and participantId.equals (mCurrentParticipant.getId ()
is true. In other cases (when mCurrentParticipant == null
or when participantId.equals (mCurrentParticipant.getId ()
is false) it returns false
which contradicts the condition than any boolean expression expected to be true
for compiler, so this Android Studio solution is more clear than another ones.