:::: MENU ::::

Saturday, April 29, 2017

Do you use Dependency Injection? Of course you do, you’re a responsible programmer, and you care about clean, maintainable, SOLID code with low coupling. You know perfectly well that New is Glue, and you understand the value of programming to interfaces, not implementations.
So do I, but please note that none of this means you should pair each and every one of your domain classes with a more or less identical interface. I suggest that you should prefer working with your concrete domain classes instead. This may sound like a dirty hack to you, but my claim is that doing this will in fact improve the quality of your code. Pairing every class with an interface, on the other hand, is an anti-pattern.
Programming to interfaces means you should try to use the most generic abstraction available to you when you program. If you have a queue of people and you need a utility method to find the tallest person, you should not do this:
public int Tallest(Queue<Person> people)
{
    return people.Max(p => p.Height);
}
That method does not need to care whether the collection of people is a Queue or something else, so you follow ReSharper’s advice and do this:
public int Tallest(IEnumerable<Person> people)
{
    return people.Max(p => p.Height);
}
However, this does not mean that if you have a domain class Foo that you need to handle somewhere, you must first create the interface IFoo and handle that:
public void ProcessFoo(IFoo foo)
{
    ...
}
Perhaps you do this because you think it is dictated by SOLID, DDD or DI, but the reality is that you are in fact introducing unnecessary complexity and duplication of code, violating YAGNI, and lowering readability and maintainability of the codebase.
So what’s actually the problem? Well, the thing is that all classes already expose interfaces to begin with. The set of all non-private class members is an interface. If you decide to create an interface IFoo definition that matches the public members of Foo, you will simply have duplicated the interface of Foo and added no real abstraction and zero value. Browsing code like this is no fun whenever you go to a definition, expecting to get to a class implementation, and just ending up in an interface, where you need to do another step to go to the implementation.
But I need this interfaces to make Dependency Injection work, I hear you say. No, you don’t. Let me demonstrate. Let’s say you have a method that needs to call a domain object in order to create an order:
public async Task<IActionResult> Order()
{
    ViewBag.OrderStatus = await orderService.Order();
    return View();
}
Now, you don’t want to do new OrderService() in there, and I totally agree with you on that. So you decide to pass an interface using constructor injection like this:
public HomeController(IOrderService orderService)
{
    this.orderService = orderService;
}
Then you just need to register your actual domain class with the container, and you’re good to go:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddTransient<IOrderService, OrderService>();
}
Guess what? All you need to do in order to get rid of that superfluous IOrderService is to, well, remove it. In your constructor, receive the concrete class instead:
public HomeController(OrderService orderService)
{
    this.orderService = orderService;
}
As for the registration, it just gets easier:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddTransient<OrderService>();
}
That’s it. You’ve now cleaned up some code. But what about unit testing? By replacing all those interfaces with concrete classes, surely I must have given up the ability to unit test my domain classes in isolation? Not at all, and I’ll show you.
Imagine that the OrderService calls a Storage class to save the new order, and that both these classes make use of a Logger class to report progress. Let’s say you want to test the Order() method, but without the Storage class talking to the database. You do, however, want to use the real Logger.
The method that we want to test looks like this:
public async Task<OrderStatus> Order()
{
    logger.Log("Doing some ordering logic here...\n");
    await storage.Save();
    return OrderStatus.Ok;
}
The Save() method that we want to mock out looks like this:
public virtual async Task Save()
{
    logger.Log("Writing to a database here...\n");
    await Task.Delay(100);
}
If only you had used interfaces, then you could easily have mocked out the dependency to IStorage. Well, guess what? You can just as easily mock out a concrete class. Here’s how this works using Moq:
[Fact]
public async void OrderReturnsOk()
{
    var logger = new Logger();
    var storageMock = new Mock<Storage>(logger);

    storageMock
        .Setup(s => s.Save())

        // Not necessary, just for illustration.
        .Callback(() => logger.Log("mocked storage"))

        .Returns(Task.CompletedTask);

    var orderService = new OrderService(logger, storageMock.Object);

    var status = await orderService.Order();

    Assert.Equal(OrderStatus.Ok, status);
    Assert.True(logger.ToString().Contains("ordering logic"));
    Assert.False(logger.ToString().Contains("database"));
    Assert.True(logger.ToString().Contains("mocked storage"));
}
So why do people keep making all those interfaces? There is quite a bit of discussion about it on the Internet, and if you’re interested in more arguments in favor or against, see here, here or here.
Please note that I’m not saying that interfaces are always bad. When they add value, they are useful. I’m only saying that interfaces that mirror one and only one class implementation is waste. Here are some cases where interfaces may be useful:
  • When there is more than one implementation of a common interface. For example, if the IStorage interface is implemented by DocumentDbStorage as well as FileStorage.
  • If you anticipate an arbitrary number of consumers that you won’t have any control over, i.e. if you’re making a public library such as a NuGet package, and you expect your class implementations to change more frequently than your interfaces.
  • When a single class is playing multiple roles. Then it can implement many interfaces, one for each role. This is basically the Interface segregation principle, an element of SOLID. There is an example here.
  • When various unrelated classes share a common loosely interpreted behavior, such as in the IPest example here.
The next time you are tempted to take a single class, extract a single interface from it, and name it the same as the class with an I in front, think twice.
Does this make sense to you, or do you disagree? Please share your opinion in the comments below.
The sample source code used in this article is available here:https://github.com/torhovland/dependency-injection-without-interfaces
Update 2017-04-24
Some have pointed out that making a method virtual, like I do with Save() above, is not without its own set of maintenance issues. It’s a design decision that you need to be conscious about.
If you have a very high test coverage of mocking tests and you are not comfortable with making your methods virtual, then sure, maybe interfaces is indeed a better option for you.
The point of this article is not to say that using DI with interfaces is bad. My point is that you shouldn’t automatically put interfaces on everything without thinking, but certainly use them when you need them.

More
A few days ago, I was answering questions on Stack Overflow when I came across one that I thought might be relevant to share with others that might have a similar issue. The issue itself revolved around Tag Helpers, and in particular, getting data attributes found on models to properly generate the appropriate attributes when rendered.
This post will introduce how to easily extend an existing tag helper for a common use-case. It will primarily focus around the use of the Input Tag Helper, the [MaxLength] annotation commonly found on string properties on a model, and how to get that to properly render the corresponding client-side maxlength attribute on the element.

The Problem with Some Tag Helpers

At present, tag helpers are extremely powerful and do a great job at figuring out which properties should and should not be rendered for a given class. Consider the following example:
[Display(Name = "Foo")]
[Required]
[MaxLength(8, ErrorMessage = "Foo cannot be longer than 8 characters.")]
public string Foo { get; set; }  
If you wanted to use a tag helper, you might define this as follows within your View:
<input asp-for="Foo" data-val="true" />  
The asp-for attribute is arguably one of the most common tag helpers that you'll encounter, and its primary purpose is to handle binding a specific property to the element that it decorates.
This works very similar to the Html.TextBoxFor() helper that you should be accustomed to. It should read the attributes that it can off of the property itself and then apply the appropriate attributes. The data-val attribute on the helper is simply to indicate that we want to use client-side validation (e.g. jQuery Validation, etc.) for this particular item.
So let's see what gets rendered:
<input data-val="true"  
       type="text" 
       data-val-maxlength="Foo cannot be longer than 8 characters" 
       data-val-maxlength-max="8"
       data-val-required="The Foo field is required." 
       id="Foo" 
       name="Foo" 
       value="" />
While the tag helper did its best, it seemed to have missed the crucial maxlength attribute that we need to enforce length validation. Let's see how we can go about extending it to support this.

Extending the Input Tag Helper

To tackle this problem, we are going to extend the existing asp-for attribute of the input tag helper and use a bit of reflection to read the [MaxLength]annotation and render it as necessary.
Let's create a new class called MaxLengthTagHelper which looks like the following:
namespace YourProject.TagHelpers  
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class MaxLengthTagHelper : TagHelper
    {
        public override int Order { get; } = int.MaxValue;

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);

            // Process only if 'maxlength' attribute is not present already
            if (context.AllAttributes["maxlength"] == null) 
            {
                // Attempt to check for a MaxLength annotation
                var maxLength = GetMaxLength(For.ModelExplorer.Metadata.ValidatorMetadata);
                if (maxLength > 0)
                {
                    output.Attributes.Add("maxlength", maxLength);
                }
            }
        }

        private static int GetMaxLength(IReadOnlyList<object> validatorMetadata)
        {
            for (var i = 0; i < validatorMetadata.Count; i++)
            {
                if (validatorMetadata[i] is StringLengthAttribute stringLengthAttribute && stringLengthAttribute.MaximumLength > 0)
                {
                    return stringLengthAttribute.MaximumLength;
                }

                if (validatorMetadata[i] is MaxLengthAttribute maxLengthAttribute && maxLengthAttribute.Length > 0)
                {
                    return maxLengthAttribute.Length;
                }
            }
            return 0;
        }
    }
}
As you can see within the Process() method, we are going to pass in the available metadata for the property and iterate through it to see if we can find the an existing MaxLengthAttribute item (if one isn't already defined):
// Process only if 'maxlength' attribute is not present already
if (context.AllAttributes["maxlength"] == null)  
{
       // Attempt to check for a MaxLength annotation
       var maxLength = GetMaxLength(For.ModelExplorer.Metadata.ValidatorMetadata);
       if (maxLength > 0)
       {
              output.Attributes.Add("maxlength", maxLength);
       }
}
You could easily extend this to check the metadata for other common data annotations and use the same basic idea to add custom attributes of your own. But for now, we will move on to actually using this particular one.

Using the Extended Tag Helper

In order to have access to this tag helper within our view, we will need to actually import it. This can generally be done within the _ViewImports.cshtmlfile, which is commonly found in most default project templates and defines any assemblies and namespaces that the views will need to access.
You'll just need to add the appropriate namespace where you defined the class and you should be good to go:
@using YourProject
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourProject
After adding that, you won't need to change your code at all and you should see that the previous code will now render as follows:
<input data-val="true"  
       type="text" 
       data-val-maxlength="Foo cannot be longer than 8 characters." 
       data-val-maxlength-max="8" 
       data-val-required="The Foo field is required." 
       id="Foo" 
       name="Foo" 
       value="" 
       maxlength="8" />
As you can see, the maxlength attribute was added to the element as expected and should now enforce the same length constraints that are present on the model within the browser.

Extending It Further

Now since you are already including the maximum length a string can be, we will probably want to include the minimum as well. This can be done by the addition of a GetMinLength() method call and including it within the Process()method to ensure that any attributes found are rendered to the element:
public override void Process(TagHelperContext context, TagHelperOutput output)  
{
    // Previous code here omitted for brevity

    if (context.AllAttributes["minlength"] == null)
    {
        // Attempt to check for a MaxLength annotation
        var minLength = GetMinLength(For.ModelExplorer.Metadata.ValidatorMetadata);
        if (minLength >= 0)
        {
            output.Attributes.Add("minlength", minLength);
        }
    }
}

private static int GetMinLength(IReadOnlyList<object> validatorMetadata)  
{
    for (var i = 0; i < validatorMetadata.Count; i++)
    {
        if (validatorMetadata[i] is StringLengthAttribute stringLengthAttribute && stringLengthAttribute.MinimumLength > 0)
        {
            return stringLengthAttribute.MaximumLength;
        }

        if (validatorMetadata[i] is MinLengthAttribute minLengthAttribute && minLengthAttribute.Length > 0)
        {
                return minLengthAttribute.Length;
        }
    }
    return 0;
}
Now if we were to decorate the property using any combination of the [MinLength] and [MaxLength] annotations:
[MinLength(2, ErrorMessage = "Foo must be at least 2 characters.")]
[MaxLength(8, ErrorMessage = "Foo cannot be longer than 8 characters.")]
public string Foo { get; set; }  
Or the [StringLength] annotation, which can be used to set both a minimum and maximum string length size:
[StringLength(2, ErrorMessage = "Foo must be between 2 and 8 characters.")]
public string Foo { get; set; }  
We should see that both the minlength and maxlength attributes are present on the rendered input element as expected:
<input data-val="true"  
       type="text" 
       data-val-maxlength="Foo cannot be longer than 8 characters." 
       data-val-maxlength-max="8" 
       data-val-required="The Foo field is required." 
       id="Foo" 
       name="Foo" 
       value="" 
       maxlength="8"
       minlength="2" />

Scratching the Surface

This really just scratches the surface is the most basic of use cases. Tag helpers can handle implementing nearly any types of functionality, from performing simple annotation / attribute additions to complex data binding scenarios. This particular example simply extended an already existing tag helper, but you can just as easily create your own and do whatever you see fit.
If you are interested in learning more about tag helpers and some of the things that they are capable of, I'd encourage you to check out some of the following resources:
More