HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Simplified if return suggestion from Android Studio

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplifiedandroidreturnsuggestionstudiofrom

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.

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.