Posts

Showing posts from 2011

Value Objects and Code Contracts

A while ago I came across an excellent presentation by Dan Bergh Johnsson on the topic of value objects. There is nothing revolutionary in this talk, but it was a good reminder of what value objects actually are and where they should be used.  While the ideas in the video stand on their own, it is interesting to see how they complement and simplify pre- and post-condition checks on methods with code contracts. Consider the following example (using Microsoft code contracts) in which a domain name is added to a collection that does not allow duplicates: public class DomainNameList { private IList<string> _domainNames = new List<string>(); public void AddDomainName(string domainName) { Contract.Requires(!string.IsNullOrWhitespace(domainName)); Contract.Requires(!Contains(domainName)); Contract.Requires(ValidationUtil.IsValid(domainName)); _domainNames.Add(domainName.Trim()); // Trim to ensure whitespace does not affect Equals

Free to Write Bad Code

The other day I stumbled across " Is it Possible to do Object-Oriented Programming in Java ", a video presentation by Kevlin Henney hosted at  InfoQ .  I had expected the same tired comparisons to Smalltalk and C++, but I was pleasantly surprised.  Despite the talk's title, it had very little to do with Java;  the bulk of the discussion centered around abstraction.  The one thing that really stuck with me was the purist notion of writing code such that concrete classes appear only to the right of "new" operators, and using interfaces everywhere else (even in concrete implementations of equals and hash code functions). So in a new project I've been experimenting with this.  I started by identifying all of the types and services I would need to deal with and defined them as interfaces.  The arguments of each method call are defined in terms of either primitives or interfaces.  Whenever I had to deal with concrete types in the underlying framework I defined i