Editorials

When Code Generators Drive You Crazy

I’ve been spending a lot of time this last week fighting and arguing with tools and frameworks. It seems like the more we want tools to automatically generate code for repeatable things, like an ORM, the more we give up on good design. The code generators tell us how to design our systems, because they only implement the happy path. As soon as we try and do anything a little out of the norm, it requires us to follow unsavory practices, because the good ones aren’t supported.

Here’s a good example. Excepting recent versions of Entity Framework, it REALLY didn’t like it when you have a one to zero or one relationship between two tables. A one to zero or one relationship is a very good database design, when you have data that doesn’t occur in a large percentage of the records in a given parent table. Sure, you can simply have a single table, and allow nulls in the columns where it doesn’t apply. SQL Server even has the ability to optimize this kind of table as being sparse.

There are some advantages to having the separate table. First, if you only want those records that are populated, calling the optional data table can result in a faster query because there are less records, and the data is contiguous on the disk. There are other scenarios that benefit as well. I’d do a Google search on the benefits of a one to zero or one relationship in a relational database engine for more examples.

Entity framework didn’t like the one to one, or one to zero or one relationships, early on, because it was unable to determine which table was the parent, and which table was the child. This has been resolved in the later versions of EF. In earlier versions you could implement the relationship with a one to zero or many relationship, in which you would simply add only a single record on the many side. This way you could fool it into knowing the parent. However, this made your code more complicated because you had to evaluate the set for null, and then get the first value in the collection. It just didn’t make good objects.

So, if you want the perfect world, roll your own code. If you want to get the happy path done quickly, use a code generator. If you don’t have time for either, it’s time for a vacation.

Cheers,

Ben