Monday, July 16, 2012

Introducing Value Objects - Functional Programming

In the previous post, we introduced Value Objects. It would be interesting to see how we can introduce such types in C#. In this post, we will be implementing a simple value object based type. This would be an immutable one as the famous saying, "Value Objects should be immutable".

In .net framework, string is a reference type but mostly it behaves like a value type. It is an example of a value object implemented as reference type. When we think about this then we immediately question why in the world it was implemented as such. Why didn't Microsoft introduced string as struct. Or generally speaking, should we be using struct or class when defining such types in C#? Well, fortunately we are not the first ones in the world who have questioned that. Please refer this discussion why it makes more sense to be implementing types for our value objects as reference types. It is better for convenience, performance and usability concerns.

Let's first introduce a simple immutable type in C#, named Barista. A barista is identified by Id. It also has a first and last name. Since this type is immutable, its members cannot be modified after constructor finishes execution. There is only one constructor which expects Id and names. After verification of arguments, it assigns them to its local members.

We will also need to override these methods so that equality checks are structural checks where member's values are checked for equality instead of their references.

Additionally we can also override equality (==) and non-equality operators as follows:

This seems logically true but it is not. Running this would show us the surprise. Basically we are causing non-limiting recursive calls between equality and non-equality operators and Equals method. This is causing the StackOverflow exception.

Let's try updating the equality by taking little advice from Microsoft.

Now we can use the code without any further exceptions!!!


No comments: