patternjavaMinor
Simplified if return suggestion from Android Studio
Viewed 0 times
simplifiedandroidreturnsuggestionstudiofrom
Problem
I have this very simple method:
I receive a warning stating that I can simplify the code in the following manner:
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.
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):
Another question is if this is actually the best approach.
You could use
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.Code Snippets
private boolean isTheParticipantTalking(ParticipantID participantId){
if(mCurrentParticipant == null) {
return false; // no one is talking
}
return participantId.equals(mCurrentParticipant.getId());
}Context
StackExchange Code Review Q#80674, answer score: 8
Revisions (0)
No revisions yet.