Faking domain logic

Using C# extensions to create the illusion of domain logic

 23 September 2014  |   27 April 2018
  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?  3 August 2018

Hiding Code Complexity

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

Webdriver Exception Handling

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

 Top