Version comparison function

I have this version comparison function in java.

Any cleaner way to write this without all the nested ‘if’ statements?

Note that the suggestions must be in Java code only.

@Override
public int compareTo(Version o)
{
    int result = this.major.compareTo(o.major);
    if (result == 0)
    {
        result = this.minor.compareTo(o.minor);
        if (result == 0)
        {
            result = this.minor2.compareTo(o.minor2);
            if (result == 0)
            {
                result = this.suffix.compareTo(o.suffix);
            }
        }
    }

    return result;
}

Edit:

Just to be clear on the ‘type’ of the fields of the Version class:

Integer major, minor, minor2;
String suffix;

Answer

If you expect often, that two versions will be the same reference, you could start your method with a check for that. And you may strip the noisy ‘this’. However, the cascading nature of the check is pretty fine expressed in the nesting – I would keep it.

@Override
public int compareTo (Version o)
{
    if (this == o)
        return 0;
    int result = major.compareTo (o.major);
    if (result == 0)
    {
        result = minor.compareTo (o.minor);
        if (result == 0)
        {
            result = minor2.compareTo (o.minor2);
            if (result == 0)
            {
                result = suffix.compareTo (o.suffix);
            }
        }
    }
    return result;
}

Attribution
Source : Link , Question Author : pdeva , Answer Author : user unknown

Leave a Comment