skip to main content

Faking domain logic

Using C# extensions to create the illusion of domain logic

 |  programming

domain driven design CSharp code smells

Sometimes, life is just a little bit more difficult than you imagined the day before. Sometimes, you have to work on a legacy codebase with custom frameworks rooted so deeply you’re having lot’s of trouble trying to build around them. To make it a bit more concrete, here’s an example: imagine a separate DLL for interfaces and a separate DLL for the implementation. This decision was made because we use NHibernate as a data mapper and not to write beautiful domain driven design code. As a result, writing domain logic methods on our “domain” objects is impossible because we have three implementations.

There are a few solutions. The first would be the classic solution, called a “service layer” where you simply dump random “domain” logic. Done.

Then there’s a slightly better solution involving abstract classes. But it makes things more complicated, and it’s not always allowed to inherit from those classes. Besides, in which DLL should you put them? Dependency Entanglement. Welcome to hotel Cali— erm, DLL Hell.

So, option number three: use extensions on those interfaces.

    public interface IVacancy
        public string Description { get; set; }

would have these implementations:

    public class FulltimeVacancy : IVacancy
        public string Description { get { // ... }; set { field = value; }}
    public class HalftimeVacancy : IVacancy
        public string Description { get { // ... }; set { field = value; }}

If I’d want to implement something like RetrieveLocation() based on for example google maps and other properties, I can place the entry point in an extension class:

    public static class IVacancyExtensions
        public static string RetrieveLocation(this IVacancy vacancy)
            // do your thing

Using the right namespace imports, I’m able to call the above method on any concrete implementation of IVacancy, regardless of it’s (DLL) location. Now, why would I want to keep code like this as close to the original object as possible? this has multiple reasons:

Domain Driven Design in C

Who says imperative languages don't do DDD?

Hiding Code Complexity

Do make it easy to read. Don't expose inner workings.

Webdriver Exception Handling

What should you do when something goes wrong with your scenario tests

A photo of Me!

I'm Wouter Groeneveld, a level 35 Brain Baker, and I love the smell of freshly baked thoughts (and bread) in the morning. I sometimes convince others to bake their brain (and bread) too. Read more about me here.

If you found this article amusing and/or helpful, you can buy me a coffee - although I'm more of a tea fan myself. I also like to hear your feedback via Mastodon or e-mail. Thanks!