torstai 4. maaliskuuta 2010

When not to implement GetHashCode() or Equals()

This question raises time to time and there seems to be no clear answer. But after working with NHibernate for five years the simple answer is don't. Of course that answer is over simplification and doesn't take account all the scenarios. In this post I'm going through one scenario.

When objects are not shared between sessions do not implement

When you only have objects living during life-cycle of session let the session's first level cache handle instances. NHibernate's first level cache will make sure that there is only one instance of your entity for each identifier.

Let's first consider why we have identifier for entities anyway? This is because databases require some kind of unique identifier to separate rows from each other. The identifier is not required at your domain model because every instance of object has it's own internal identity that separates it from other instances. The requirement of identifiers comes from the fact that databases are not planned to store objects. My tip would be that if you ever require to access identifier property from your model you are doing something wrong. Identifier only exists because it is required by your database.

If you do implement GetHashCode or Equals you will get trouble when creating new unsaved entities. The most obvious way to implement GetHashCode or Equals would be by associating them with identifier. But what happens when you create two new instances? If you use automatic identity generation provided by database those entities will have uninitialized identifiers until you save them for first time.

When you don't implement GetHashCode and Equals everything will work just fine as long as entities are not share between sessions. From the point of view of your model the identifiers don't exists. Actually I wonder why NHibernate don't just generate identifier properties on-fly when it generate proxies.

1 kommentti:

  1. .NET development, ASP development, SharePoint development,.NET development Microsoft development , software development, Singapore – Total eBiz Solutions Home