Skip to main content

Posts

Showing posts from August, 2018

Why using XOR might not be a good hash code implementation?

Using XOR for computing hash codes works great for most of the cases specially when order of computation does not matter. It also has the following benefits:
XOR has the best bit shuffling properties of all bit-operations and provides better distributions of hash values.It is a quick single cycle operation in most computer Order of computation does not matter. i.e. a^b = b^a However, if ordering of elements matter then it is often not a good choice.

Example
For simplicity consider you have a class with two string properties named Prop1 and Prop2 and your GetHashCode returns the xor of their hash code.

It will work fine for most of the cases except cases where same values are assigned to different properties. It will generate same hash-code i.e. collision in that case as can be seen in the below example.


However, using the modified approach as recommenced by Joshua Bloch's in Effective Java which uses prime multiplication and hash chaining provides more uniform distribution and a di…

Interesting bug - Line endings and Hash Code

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.

Bug
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 fou…