patterncsharpMinor
IComparable implementation for a class representing a version
Viewed 0 times
icomparableversionforimplementationclassrepresenting
Problem
I have an UpdateId class which represents some kind of version (like AssemblyVersion). UpdateId has three int values (listed in their compare priorities order): Year, ReleaseNumber and Revision.
How can I make my CompareTo method better? It looks clumpy to me.
How can I make my CompareTo method better? It looks clumpy to me.
public int CompareTo(object obj)
{
if(obj == null) return 1;
var updateId = obj as UpdateId;
if (updateId != null)
{
int yearCompare = this.Year.CompareTo(updateId.Year);
if (yearCompare == 0)
{
int releaseNumberCompare = this.ReleaseNumber.CompareTo(updateId.ReleaseNumber);
if (releaseNumberCompare == 0)
{
return this.Revision.CompareTo(updateId.Revision);
}
return releaseNumberCompare;
}
return yearCompare;
}
else
{
throw new ArgumentException("Object is not an UpdateId");
}
}Solution
You could change it to reduce the "arrow style" like so
which will save you some horizontal spacing and some not needed variables, because they all meant the same so I changed them to
public int CompareTo(object obj)
{
if(obj == null) { return 1; }
var updateId = obj as UpdateId;
if (updateId == null)
{
throw new ArgumentException("Object is not an UpdateId");
}
int compareResult = this.Year.CompareTo(updateId.Year);
if (compareResult != 0) { return compareResult; }
compareResult = this.ReleaseNumber.CompareTo(updateId.ReleaseNumber);
if (compareResult != 0) { return compareResult; }
return this.Revision.CompareTo(updateId.Revision);
}which will save you some horizontal spacing and some not needed variables, because they all meant the same so I changed them to
compareResult.Code Snippets
public int CompareTo(object obj)
{
if(obj == null) { return 1; }
var updateId = obj as UpdateId;
if (updateId == null)
{
throw new ArgumentException("Object is not an UpdateId");
}
int compareResult = this.Year.CompareTo(updateId.Year);
if (compareResult != 0) { return compareResult; }
compareResult = this.ReleaseNumber.CompareTo(updateId.ReleaseNumber);
if (compareResult != 0) { return compareResult; }
return this.Revision.CompareTo(updateId.Revision);
}Context
StackExchange Code Review Q#96329, answer score: 4
Revisions (0)
No revisions yet.