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

Comparison methods for Photo objects

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

Problem

I'm unsure of how to Name and clearly distinguish between methods that deals with comparisons.

I know of the following two established concepts:

.Equals: A method to see if two objects refer to the same instance

.Compare: A method often used when determining sort order among objects

But what to name a method when you are interested to see if two different object instances refer to the same "logical" object, or when comparing values of two different object instances? Let me give you an example with a class named Photo.

```
public class Photo : IEquatable
{
public string FileName { get; private set; }
public string InFolder { get; private set; }
public string FullFilePath { get; private set; }
public string FileExtension { get; private set; }
public long FileSize { get; private set; }
public DateTime FileLastModified { get; private set; }
public DateTime FileCreated { get; private set; }
public ExifData EXIF
{
get
{
if (this._exif == null)
LoadExtendedProperties();
return this._exif;
}
set { this._exif = value; }
}
public Photo(string fullFilePath)
{
//...
}
public override int GetHashCode()
{
return this.FullFilePath.GetHashCode();
}
private void LoadExtendedProperties()
{
//...
}
public bool Equals(Photo other)
{
if (object.ReferenceEquals(this, null) || object.ReferenceEquals(other, null))
return false;
if (object.ReferenceEquals(this, other))
return true;
else
return false;
}
///
/// Do they refer to the same photo (file)
///
public bool UnnamedCompareMethodA(Photo other)
{
if(object.ReferenceEquals(other, null))
return false;
if (this.FullFilePath == other.FullFilePath)
return true;
else
return false;
}
///
/// Do al

Solution

You seem confused. Given two objects, a.Equals(b) tests whether they have equivalent content. Basically, what you wrote as UnnamedCompareMethodB() should actually be the Equals() method.

I wouldn't bother with defining an UnnamedCompareMethodA() at all. If someone wants to compare objects by FullFilePath, they can just write a.FullFilePath.Equals(b.FullFilePath).

Furthermore, calling object.ReferenceEquals(this, null) makes little sense. If the object were indeed null, the code would have already crashed with a NullReferenceException before then.

Context

StackExchange Code Review Q#157651, answer score: 4

Revisions (0)

No revisions yet.