Please explain the technique used in this code to verify the object’s equality and identity.

Please explain the technique used in this code to verify the uniformity and identity of objects.

It is better if you can provide me any link to a web link / book for a detailed discussion.

[Serializable] public abstract class BusinessObject<T> : IBusinessObject where T : BusinessObject<T> { private int? requestedHashCode; public virtual int ID { get; set; } public virtual bool Equals(IBusinessObject other) { if (null == other || !GetType().IsInstanceOfType(other)) { return false; } if (ReferenceEquals(this, other)) { return true; } bool otherIsTransient = Equals(other.ID, default(T)); bool thisIsTransient = IsTransient(); if (otherIsTransient && thisIsTransient) { return ReferenceEquals(other, this); } return other.ID.Equals(ID); } protected bool IsTransient() { return Equals(ID, default(T)); } public override bool Equals(object obj) { var that = obj as IBusinessObject; return Equals(that); } public override int GetHashCode() { if (!requestedHashCode.HasValue) { requestedHashCode = IsTransient() ? base.GetHashCode() : ID.GetHashCode(); } return requestedHashCode.Value; } } 

What is a transition object?

+4
source share
2 answers
  • first checks to see if other instance of the same type as the current object. If not, they are not equal.
  • then performs referential equality to check if other is the same as the current object. If they are obviously equal
  • If both other and the current object are temporary (i.e. not yet saved), they do not have an identifier, so they cannot be compared by identifier. Instead, they are compared by reference. (as Mark Gravell noted in the comments, the test to check if the object is transient is broken, it makes no sense to compare int with default (T))
  • In the end, their identifiers are compared; objects are considered equal if they have the same identifier
+3
source

I think what the code is trying to do is say "it still has an identifier", i.e. the transition object can (if I read the code correctly), which has not yet been saved to the database. Then equality is defined as:

  • If it has an identifier, does it match? (even for different instances of the same type)
  • If it does not have an identifier, this is the same instance of the object (link)

Unfortunately, the implementation seems to be completely broken, since Equals(ID, default(T)) meaningless when T is something completely different (a BusinessObject<T> ) - hence default(T) will always be null , and the ID will never be null (it cannot be null). Therefore, nothing will ever report the passing.

In addition, this code:

 if (null == other || !GetType().IsInstanceOfType(other)) 

highly ineffective. I suspect that something related to as would be much preferable, but then again: the code looks like this ... tortured ... that I don't want to guess the intent.

+2
source

Source: https://habr.com/ru/post/1379634/


All Articles