Sunday, July 20, 2008

Linq To Sql and Value Objects

Unfortunately Linq to SQL lacks support for Value Objects. This is a big limitation when you do Domain Driven Design as we do it on a project that I'm currently involved. We didn't use this pattern so far but last week there was no way around it. I had to implement a feature based on the stock of monetary units. I identified an object MonetaryUnitStock that represents the stock for a monetary unit like e.g. 10 Swiss francs. I didn't want to care about identity for that object and I wanted it to be immutable.

For my mentioned feature I had no requirements for querying. So the implementation with Linq to SQL was straight forward. Here is the code in C#.

public struct MonetaryUnitStock: IEquatable<MonetaryUnitStock>
{
private readonly int _numberOfUnit;
private readonly MonetaryUnitType _type;

public MonetaryUnitStock(MonetaryUnitType type, int numberOfUnit)
{
_type = type;
_numberOfUnit = numberOfUnit;
}

public int NumberOfUnit
{
get { return _numberOfUnit; }
}

public MonetaryUnitType MonetaryUnitType
{
get { return _type; }
}

public bool Equals(MonetaryUnitStock other)
{
return MonetaryUnitType.Equals(other.MonetaryUnitType) && this.NumberOfUnit.Equals(other.NumberOfUnit);
}

public override bool Equals(object obj)
{
if(obj is MonetaryUnitStock)
{
return Equals((MonetaryUnitStock)obj);
}
return false;
}


public override int GetHashCode()
{
return MonetaryUnitType.GetHashCode() ^ NumberOfUnit.GetHashCode();
}
}

    partial class MoneyList
{
private MonetaryUnitStock? _monetaryUnitStockUnit100;

public MonetaryUnitStock MonetaryUnitStockUnit100
{
get
{
if (_monetaryUnitStockUnit100 == null)
{
_monetaryUnitStockUnit100 = new MonetaryUnitStock(MonetaryUnitType.Unit100, NumberOfUnit100);
}
return _monetaryUnitStockUnit100.Value;
}
set
{
if(value.MonetaryUnitType != MonetaryUnitType.Unit100)
{
throw new ArgumentException("MonetaryUnitStockUnit100 expects MonetaryUnitType.Unit100");
}
_monetaryUnitStockUnit100 = value;
_NumberOfUnit100 = _monetaryUnitStockUnit100.Value.NumberOfUnit;
}
}
}


I used the DBML designer for creating this simplified example. In the designer I marked the NumberOfUnit100 attribute as private to just provide the Value Object to the outside. So client just can set and get MonetaryUnitStockUnit100 and have no access to the underlying simple type.

The reason that I implemented the MonetaryUnitStockUnit100 Property with lazy loading is, that Linq to SQL provides no interception point when reconstituting an object from persistence. The OnCreated() method generated by the designer is not suitable as it is called before the actual values are set.

Monday, March 24, 2008

Using LINQ with Text Files

I'm currently reading the book LINQ in Action which I can highly recommend to all who want to get started with LINQ. In one of the first chapters there is a nice example on how you can use LINQ with text files (originally posted by Eric White). Rather than reading all lines of the file into memory and then query it, the example uses deferred execution with an extension method on the class StreamReader.

Inspired by this example I wrote a simple file reader that can read structured non-XML data from text files. As you can see in the Process method in the code below the text file is queried and processed line by line. Objects are created on the fly, as you loop through the results. This technique allows you to work even with huge files.

public class RecordReader{
private Dictionary<string, IReaderStrategy> _strategies = new Dictionary<string, IReaderStrategy>();
private const char Comment = '#';
private int _typeFieldLength;

public RecordReader(int typeFieldLength)
{
_typeFieldLength = typeFieldLength;
}

public IList Process(StreamReader input)
{
var result =
from line in input.Lines()
where !IsBlank(line)
where !IsComment(line)
select GetStrategy(line).Process(line);
return result.ToList();
}

private IReaderStrategy GetStrategy(string line)
{
string typeCode = GetTypeCode(line);
if(!_strategies.ContainsKey(typeCode))
{
throw new NoStrategyDefinedException("No strategy defined for code " + typeCode);
}
return _strategies[typeCode];
}

private static bool IsComment(string line)
{
return line[0] == Comment;
}

private static bool IsBlank(string line)
{
return string.IsNullOrEmpty(line);
}

private string GetTypeCode(string line)
{
return line.Substring(0, _typeFieldLength);
}

public void AddStrategy(IReaderStrategy arg)
{
_strategies[arg.Code] = arg;
}
}

You can download the full source code from here

Wednesday, January 30, 2008

Unit Testing Legacy Code

After my short HTML/CSS intermezzo I'm back to the business logic programming. Even though it was instructive to do web design and presentation logic I'm happy that I can dive into the lower layers now. With this change I can also switch to my preferred way of developing software, which means TDD.

Everyone who ever wanted to do TDD in a code base that was not designed for testability knows how hard it is. The hardest part is certainly to break dependencies so you can unit test a class or method in isolation. In my last project I was involved we had quite a large code base before we started to write unit tests. With the support of Typemock we could work around the untestable pieces and TDD got possible.

Unfortunately I can't use Typemock on my current project. So I have to get back to other techniques that I learned from "Working Effectively with Legacy Code" by Michael Feathers. Here are the techniques I use a lot:

  • Subclass and Override Method. Create a subclass of the class and override the method to break the dependency.
  • Break out Method Object. Perhaps you can't get a method under test. Create a new class with the method under test.
  • Sometimes it's not possible to create an instance of an object because there are too many dependencies. Expose the method under test as a static method so it's easier to test.
  • Expose private Method. To access a private method from your fixture subclass the class and expose the method.
Even though its a little bit more work in comparison of using Typemock I think the use of these techniques results in more readable test code.

Thursday, December 13, 2007

The Agile Programmer With The Cowboy Hat

I recently got involved in a new project. It's not a project from my company. We just provide a few developers (including me) on a body leasing basis. We have to graphically redesign a web shop with some small changes in functionality. The process that we follow you could describe as a mix between waterfall and cowboy coding. The good thing is that we have a close collaboration with the product owner (yes, we have one) and a small self organizing team. But when I compare it to the project that I was involved before it's a totally different functioning.

In my last project we did scrum. Our level of scrum adoption was not too bad (7 yes answers in the nokia test). We had a good self organizing team with motivated people. We improved from sprint to sprint and ended as a very effective team.

Now, I realized once more how important practices like time-boxing, prioritized backlog and developer estimating are.

So what can you do as a an agile programmer if these key practices are missing?

Well, the good thing is that agile is not an all or nothing approach. You don't have to adopt all the practices at once. If you do that, changes are high that you will fail, especially when you have no people with agile experience in the team or support from an agile coach. As a developer your possibilities to change something are limited as well. But I think if you are an experienced agile developer and everything in your body resists against heading blindly for disaster you have to change something. Even if it's just the advocating of approved developer techniques. As I'm more a web designer than a programmer right now I can't to the last thing I mentioned. So I targeted the organizational level and introduced the backlog today .

We already had some work packages identified that where bundled into a gant diagram. This diagram was out of date from the first day of development and wasn't adjusted from that day on. So I translated this information into a prioritized product backlog and presented it to the product owner, the project manager and the team. The reaction was positive. The project manager was surprised when he saw how much work is still not done.

It's not a revolutionary change. But it's a small step towards improvement.

Sunday, November 18, 2007

NUnit Test Templates for ReSharper

Every time when I create a new unit test in visual studio I bother me that I have to type the same 4 to 5 lines of code . I was too lazy to create a visual studio or resharper template for that. Fortunately not everybody is as lazy as me:

MbUnit and NUnit Test Templates for ReSharper


Monday, November 5, 2007

Scrumbreakfast

I just came across this blog where jp anounced a scrum breakfast on November 7, 2007 at Namics in Zurich.

Great stuff. Could be of interest to our Scrum Master.

Old School Book Reading

In my last post I wrote about reading Code to improve your software development skills. Beside of that I read blogs, news and E-Books to hang in there. Althought they are great resources for learning, I prefer to read old school hard-bound books that I can cuddle up with in my bed.

Here is my list of recommended reading ...

Architecture, Design & Patterns
Agile Software Development
.NET Programming