Replace this if-then-else statement by a single return statement

前端 未结 6 1312
天命终不由人
天命终不由人 2020-12-21 01:13

While solving sonarQube issue i face the below warning,does any one tell me how to overcome this warning

Method:-

@Override
    public boolean equals         


        
6条回答
  •  难免孤独
    2020-12-21 01:42

    I received a similar kind of warning message when using sonarlint "Return of boolean expressions should not be wrapped into an "if-then-else" statement" this was my code previously,

    if (val.isEmpty()) {
        switchCompat.setChecked( false );
    } else {
        switchCompat.setChecked( true );
    }
    

    now i changed it to,

    boolean checked = val.isEmpty();
    switchCompat.setChecked( checked );
    

    According this question, it is similar to,

    @Override
    public boolean equals(Object obj) {
        Division other = (Division) obj;
        if (this == obj)
            return true;
        else if (obj == null)
            return false;
        else if (getClass() != obj.getClass())
            return false;
        else if (divisionId != other.divisionId)
            return false;
        else
            return true;
    }
    

    Similarly, it can be resolve like this,

    @Override
    public boolean equals(Object obj) {
        boolean success;
        Division other = (Division) obj;
    
        if (this == obj)
            success = true;
        else if (obj == null)
            success = false;
        else if (getClass() != obj.getClass())
            success = false;
        else if (divisionId != other.divisionId)
            success = false;
        else
            success = true;
        return success;
    }
    

提交回复
热议问题