I recently came across an interesting bug which emphasize how different line endings format can break your custom equality implementation if you do not carefully consider them.
Context
We have an application that periodically updates the local assets with latest updated resources. In a nutshell, it makes an web api call to get the latest set of metadata and compare them against a locally stored metadata file. If they differs then we update the locally stored metadata file and download new/updated resources.
For a particular asset, associated metadata file was always getting updated although there were no visible changes detected using the revision history.
Investigation
My obvious suspect was the code responsible for doing the equality check between local metadata and the metadata received from the Web API.
For verification, I setup a conditional break-point which will be hit when the equality returns false. After my debug hit the break-point, I looked into all the properties and found that one of them was returning false. It was a list of tag objects and we were doing an HashSet equality comparison on that list. Something similar to below pseudo code:
Although, I had narrowed down the issue it was still not clear which object from the list was actually throwing the equality to false. So I decided to look into the hash-codes for this two list of objects.
Upon looking into the hash code, I discovered that one of the hash-code was different between the compared objects which happened to be at position 3. A quick lookup on the value at that position and viola!. One of them contains line endings as '\r\n' = CR + LF while the one from the web api contains '\n' = LF.
Most text editor will not display the different line endings in default view also line endings could be OS specific. Hence, it seems like nothing has been changed in the file. However, as they contains different values my custom equality implementation along with the get hash-code function generates different hashes for them and thus the equality returned false.
Here is a simplified version of the original class which implements IEquatable of T
Fix
Updating the object property getter to use consistent line ending. Basically doing a Regex replace with a '\r\n'.
After the above change is in place, hash-code and hence the equality will be same for object with different line endings format. This will give us the expected result and our metadata file will not get unnecessarily updated.
Lesson Learned
Be mindful of different line endings, null values and sometimes different culture settings when implementing a custom equality based on string properties.
Comments