I have read that it is a bad idea to take aliasing into account when implementing equals.
An example would be equals for File.
I was wondering why is it a bad idea? Simply because the implementation is harder to be correct?
If FileA and FileB refer to the same file but have different path names why should they be not equal?
I have read that it is a bad idea to take aliasing into account
Share
Making equals() return true for aliased filenames that point to the same actual file is a bad idea because it violates common assumptions about the behaviour of equality.
Consider the following examples:
Hence we can see that taking aliasing into account would produce some unexpected behaviour for two supposedly “equal” objects. This is likely to cause strange and subtle bugs in the future when people make incorrect assumptions.
A secondary but also relevant concern is that taking account of aliasing may add considerable implementation complexity and performance overhead. You normally want
equals()to be very efficient since it may get called often: if it is forced to make IO calls to the operating system to determine file aliasing then this is unlikely to be the case.In this situation I would implement a completely different function that tests for pointing to the same physical file –
refersToSameFileor something similar. This allows you to use a more descriptive name for the operation and avoids messing up expectations about equality behaviour.