So I have a value object, (arbitrarily say money), and I want to implement equality for it. I am aware of the intended/default behavior for == and .Equals() (reference and data equality).
In this case though, I want to be able to compare two objects, and say that they are equivalent for calculations (e.g. 1m and 3 ft are equivalent)
however for persistence (using NHibernate, where isDirty I think depends on equality), user display and selection of currency, I want them to be considered different.
Should I, in this case,
== and .Equals() (and which should do what), .IsEquivalent() (I'd prefer not to do the latter)Is there a best practice/pattern I should follow? Thanks
Edit: i got some responses regarding changing exchange rates. so updating for clarity. lets say height, and not currency
I'm more concerned about practices and patterns, as opposed to implementing currency. Basically, the same approach to a person's height, where height is a value object, ({1,m} to {3,ft}, where 1m is always "equal"/"equivalent" to 3ft)
I would not treat 1.0 USD as equal to 0.63 GBP. In order to check for equality of monitary value, you'd need more information than just the two values - you'd also need the current exchange rate, etc. This is especially true, as the same two values won't be equal consistently, and equality should always be true if the two values are ever equal.
As such, a method, such as AreEquivalentMonitaryValues(), seems appropriate - especially given that extra info is required.
Since you want different definitions of equality depending on the context you'd want to use an IEqualityComparer.
As Reed suggests equality for the type itself should really mean, "always and forever are equal" rather than equal for the current exchange rates, but having an IEqualityComparer just means that, "from the point of view of this comparer, they are equal". From there you can have your ExchangeRate type, or something that is given an exchange rate, be able to create an IEqualityComparer<Money> object that represents equality for a given exchange rate. That equality comparer can then be used to compare various types of currencies for equality.
Another approach entirely would be to create an "invariant currency", and give your class ToInvariant and FromInvariant methods so that non-invariant currencies are not equal (ever) and invariant currencies can be equal despite the currency that generated the invariant value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With