patternjavaModerate
Version comparison function
Viewed 0 times
versionfunctioncomparison
Problem
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.
Edit:
Just to be clear on the 'type' of the fields of the Version class:
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;Solution
One point which I may suggest is reorder
Also, I think you can omit
if statements to reduce indentation:@Override
public int compareTo(Version o)
{
int result = this.major.compareTo(o.major);
if (result != 0)
{
return result;
}
result = this.minor.compareTo(o.minor);
if (result != 0)
{
return result;
}
result = this.minor2.compareTo(o.minor2);
if (result != 0)
{
return result;
}
return this.suffix.compareTo(o.suffix);
}Also, I think you can omit
this keyword.Code Snippets
@Override
public int compareTo(Version o)
{
int result = this.major.compareTo(o.major);
if (result != 0)
{
return result;
}
result = this.minor.compareTo(o.minor);
if (result != 0)
{
return result;
}
result = this.minor2.compareTo(o.minor2);
if (result != 0)
{
return result;
}
return this.suffix.compareTo(o.suffix);
}Context
StackExchange Code Review Q#1934, answer score: 13
Revisions (0)
No revisions yet.