Brendan Enrick

Daily Software Development

Parameter and Return Type Interfaces

At some point, I’m sure you’ve had someone suggest that you use an interface instead of a concrete class as a dependency. Assuming you’re following the Interface Segregation Principle, that could be exactly what you want to do. Well written interfaces can make your code much simpler and more clearly define your dependencies. That’s why Interface Segregation Principle is one of those popular SOLID principles you’re always hearing about.

NP-Interface-Segregation

I recently read an interesting tweet from Derik Whittaker talking about using IEnumerable when an ICollection or IList would be the better choice. 

Ugg, may want to fix your code rather than do this "// ReSharper disable once PossibleMultipleEnumeration"

This move toward making everything IEnumerable<T> is a trend happening across the C# community. I believe that ReSharper (a tool I use and love) is leading to some of this. When you write a method that takes in a collection as a parameter, and your method does a foreach over that collection, ReSharper will suggest (correctly) to change it to an IEnumerable. This is because you only enumerated it once, and that means that you can be more relaxed in your requirements.

Side Note: IEnumerable is not technically the requirement for a foreach loop.

The problem people run into with IEnumerables is that they’re not all collections. IEnumerable<T> just means that there is a method to get an Enumerator. In simple terms, I mean that it’s possible to walk through the items in the enumerable one at a time. Sometimes that requires work that’s more than constant time to get to the next item in the enumerable class. The comment that Derik mentioned in his tweet is one that tells ReSharper to not warn you about a possible issue. That issue is that you might be doing the work of walking through the enumerable more than once. When it sees an enumerable that is enumerated for a second time, you’ll receive this warning.

Keep Your Method Parameters Permissive

3364773646_ebc547a3fa_o

When you’re making a method parameter, you want to make sure that you’re only requiring exactly what you need. In doing this, you’ll likely create interfaces following the Interface Segregation Principle. When dealing with collections, you’re likely to accept an IEnumerable<T> if you only enumerate once. You might accept an ICollection<T> if you need to enumerate a couple of times, allow adding and removing, or need to count the items. If your collection needs random, array-like index access, you should consider using IList<T>. 

This allows the caller of your method to give you whatever they have at the time. You really don’t care as long as it has what you need. If their object is an IEnumerable that isn’t also an IList, they can convert it before providing it to you. Working this way makes your API much more flexible, since you’re making your minimum requirements clear.

Return Usable Types From Your Methods

6555544311_79789a44b9_o

Sadly, I see the reverse being pushed as a positive. You will find information telling you to return IEnumerable<T>, so that you can easily change. This, however, means that you’re providing your method’s consumer with no information about the object they’re receiving. If they need access to array-like indexing, they have to call ToList() on your return value in order to use it.

Since ICollection<T> implements IEnumerable<T> and IList<T> implements ICollection<T> and IEnumerable<T>, you can return an IList<T> allowing your method’s caller to use IList<T>, ICollection<T>, or IEnumerable<T> depending on their usage. You’re using an interface and still giving the consumer the power of choice. You can avoid tightly coupling to a concrete implementation while still providing a useful return value.

I almost never return IEnumerable<T>. I don’t know that the return value will only be enumerated once. That’s outside my current layer of abstraction, so I shouldn’t be dealing with it. The safe bet is just to return a useful collection if that’s what I have. If my value really is enumerable, but not a collection, I will return an IEnumerable. In all other cases, it should be a more useful interface. lists an collections really are cohesive concepts that should be grouped into one object when needed.

Working with Interfaces - Practical Uses

Expanding on an article I wrote a couple of years ago where I explained interfaces in C#, I’d like to explain why people should use interfaces. I received an email from a reader of my ASP Alliance article. He understands how interfaces work, but he’s trying to see why so many people are raving wildly about their greatness. His questioning of them is great, because it really is not obvious why interfaces are useful. Anyone who says otherwise is just trying to brag.

A couple of years ago, you wrote an article for ASP Alliance called "Understanding Interfaces." Once again, I saw how the code works, once again, I failed to see how it will benefit me.

Here's where everything breaks down for me: You create an interface with just method, property and event signatures. Then you inherit them in a class, recreate these same signatures and write the code to implement these methods and properties.

So I’ll start by mentioning that nearly all patterns, practices, principles, etc. in software development are based on code reuse. One of the most important reasons for code reuse is change. Developers are always responding to and creating changes. We must mitigate the risks of change, identify where changes will occur, and we must make changes.

Right about now you might be thinking, “but interfaces don’t reuse code. They just force you to implement new code. Using inheritance would be the way to achieve code reuse.” You ate technically correct. You understand how interfaces work, but you’re not seeing why we use interfaces. Interfaces themselves do not give us code reuse at all, however, they enable us to achieve code reuse.

Remember that I said that we must identify where changes will occur. Making this identification allows us to isolate changes thus mitigating the risks of changes and allowing us to make changes. Isolating the places that change also allow us the reuse the code which does not change, so by keeping some parts separate we can reuse others. The interfaces are for the places we can’t reuse the code.

Interfaces are “places of change”. Each implementation of the interface is a variation on how that required piece of the puzzle could have been implemented. This is contrary to how you’ll see a lot of interfaces used. It is sometimes difficult to see this as the behavior of interfaces, because people overuse interfaces.

As I see it, I could have saved a whole lot of time by not creating the interface in the first place! I mean, it's not doing any work. I still have to create the signatures in the class. Why on Earth do people praise these things and call them the answer to multiple inheritence? They don't do anything!

It is mostly true that interfaces don’t do anything. As far as being executable code is concerned an interface is basically just a worthless extra step, so why would we use them? Declaring an interface is like saying, “there is more than one way that this behavior could be implemented, but interactions with this behavior should be done this way only.” Having that common “interface” allows us to use any of these implementations interchangeably.

When to Use Interfaces

Some people would recommend that interfaces should be used everywhere. I’ve heard people say that no variable should be declared with a concrete type if it can be avoided. That may be a valid point, but if you’re just learning how interfaces can be useful that is a bad approach. If you don’t see value in interfaces, you will certainly not see the value of them when people use them everywhere. This washes them out and obfuscates their purpose.

Interfaces are used for logic which will have multiple or changing implementations. This means that we should use them in places where we will out of necessity have duplicate logic. Using the interface is what allows us to do this. Take a look at this code for composing a letter.

public string ComposeLetter(string recipientName, 
string messageBody, bool isFormal)
{
string messageText = string.Empty;
if (isFormal)
{
messageText += GetFormalGreeting(recipientName);
}
else
{
messageText += GetCasualGreeting(recipientName);
}

messageText += messageBody;

if (isFormal)
{
messageText += GetFormalSignature();
}
else
{
messageText += GetCasualSignature();
}

return messageText;
}

Notice how we have these flow control operators dictating how the code will execute. What will happen if we need to have a third option for greetings and signatures for family members? We might add another else-if or we might use a switch. Either way this code gets larger and changed every time.

However, if we identify the aspects of the code that are changing we can isolate them and mitigate the risks of changing the code by keeping separate the logic which has multiple implementations. Notice we have already used one form of encapsulation by keeping each of those pieces of logic in separate methods. The logic we haven’t encapsulated is the flow control.

We can create an interface for it. The best name I’ve got for now is IFormalityGenerator, which is not a great name, but it will do for now. I’ll create that interface with two methods: GetGreeting and GetSignature. Very simple interface. Now we can rewrite our method to look like this.

public string ComposeLetter(string recipientName, string messageBody, 
IFormalityGenerator formalityGenerator)
{
string messageText = string.Empty;

messageText += formalityGenerator.GetGreeting(recipientName);

messageText += GetMessageBody();

messageText += formalityGenerator.GetSignature();

return messageText;
}

We now just make the decision sooner and only once which implementation we are using. If this is a formal letter we will use the FormalFormalityGenerator. If it is casual we will use the CasualFormalityGenerator. Down the road when we create one for family members we can just go and create an implementation for the FamilyFormalityGenerator. We’ve made it so we create new code each time instead of going and changing the existing code in this method.

The power of an interface is in its ability to encapsulate the volatile aspects of a program and isolate that which can be reused more easily.

Implementing IEnumerable and IEnumerator

Working with a foreach loop is the primary reason to implement the IEnumerable and IEnumerator interfaces. You’ll want one of each of these to work with the loop.

I am going to do an example DateRange class which will implement IEnumerable<DateTime> and will allow us to iterate through a non-existent collection of DateTime objects.

Note: I am aware of the fact that I could achieve the same result with a for loop. I find the foreach loop more readable.

First we need to create a basic DateRange class. A range can be defined as a StartDate and an EndDate, so I’ll start there.

public class DateRange
{
    public DateRange(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
 
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

So this DateRange could be useful on its own, but we want to be able to iterate this collection using a foreach. So to start we need to implement the IEnumerable<DateTime> interface.

public class DateRange : IEnumerable<DateTime>
{
    public DateRange(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
 
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
 
    public IEnumerator<DateTime> GetEnumerator()
    {
        return new DateRangeEnumerator(this);
    }
 
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

 

Notice here that we now need to get the IEnumerator<DateTime> object in the GetEnumerator() method. I jumped the gun a bit and I’ve called a class that doesn’t exist yet. I’ll make another class and implement the required methods for the IEnumerator interface.

public class DateRangeEnumerator : IEnumerator<DateTime>
{
    private int _index = -1;
    private readonly DateRange _dateRange;
 
    public DateRangeEnumerator(DateRange dateRange)
    {
        _dateRange = dateRange;
    }
 
    public void Dispose()
    {
    }
 
    public bool MoveNext()
    {
        _index++;
        if (_index > (_dateRange.EndDate - _dateRange.StartDate).Days)
            return false;
        return true;
    }
 
    public void Reset()
    {
        _index = -1;
    }
 
    public DateTime Current
    {
        get { return _dateRange.StartDate.AddDays(_index); }
    }
 
    object IEnumerator.Current
    {
        get { return Current; }
    }
}

 

These are the handful of methods we implement for the IEnumerator<DateTime> interface. These are all about moving to the next object and getting the current object. Resetting and Disposal of the object are less important, so make sure you read MoveNext and Current.

Keep in mind here that I could have used a collection for this, but I didn’t because I don’t need one. The calculation to get the items was easy enough.

var dateRange = new DateRange(DateTime.Today.AddDays(-6), DateTime.Today);
foreach (DateTime date in dateRange)
{
    Console.WriteLine(date.ToShortDateString());
}

Output:

10/20/2009
10/21/2009
10/22/2009
10/23/2009
10/24/2009
10/25/2009
10/26/2009

Getting Around a Lack of Interfaces With Partial Classes

One pain point which comes along often when working with others' libraries are the classes that are not open and implementing interfaces. A lot of the classes we developers use every day implement no interfaces. Since the class is out of my control, I obviously cannot give it an interface, so I need some other way to work with it. This creates a problem when we need to mock out the class. There are ways in which we can get around this though.

Wrapping Classes

In my opinion, the most dependable workaround to be able to mock out and test a class is creating an interface-implementing wrapper around the class we want to mock and using that instead. This one works very well, but it forces you to create an interface and a class even though there is already a class in existence.

Partial Class Interface

As the name of this post says, partial classes can be very important when presented with this problem. If a class is not implementing an interface, but it is a partial class, you can give it an interface it is already implement.

If a class is partial you can give it an interface which defines the methods it already implements.

So now I am going to present an example. For this example, we will have a class called "BrendanMailer". This class is not implementing an interface, which means that if we want to remove this dependency we need to come up with some solution that lets us program against an interface.

public partial class BrendanMailer
{
    public void SendEmail()
    {
    }

    public void SomeNonImportantMethod()
    {
    }
}

For this we could obviously use the wrapper method, but we can also do something a lot easier. Thanks to the smart creator of that class, there is a partial keyword in there. This allows us to leverage a very powerful trick, because we can now create our own interface. The interface can include only the methods we want it to, which is in some ways better than if the interface had been predefined.

public interface IBrendanMailer
{
    void SendEmail();
}

So now I have a custom interface to work with and program against. I now just add that into another part of this partial class and tell that one I am implementing the interface. I don't have to implement the methods, because they already are implemented in the original part of this partial.

public partial class BrendanMailer : IBrendanMailer
{
}

In my production code I will inject the BrendanMailer class, and in the tests I will mock it out or use a fake or something. This is very powerful and doesn't clutter much at all, because I can hide this partial away in a folder in my project and ignore it for a long time.

Explicitly and Implicitly Implementing Interfaces

I read an interesting blog post from Joydip Kanjilal where he described an interesting little trick with interfaces. I, being a bit of a fan of interfaces, read the post and thought I'd throw my $0.02 in also. I couldn't pass up an opportunity to talk about interfaces. He first shows simply how to create an interface and how to implement the interface implicitly. The difference between implicitly and explicitly writing this code is what creates the different circumstances Joydip shows in his demonstration.

I'll start where he did with an interface. I'll name my interface IBloggable and I'll have a class PostContent which implements the interface.

public interface IBloggable
{
    void SendToBlog();
}

public class PostContent : IBloggable
{
    public void SendToBlog()
    {
        // Send this content to a blog
    }
}

Ok so this is the implicit implementation of the interface. Basically all I mean when I say explicitly and implicitly is whether or not you're going to define everything. If I define something explicitly I have defined everything and made it perfectly clear. I have included every detail required for precise interpretation. Notice above I have not specified to which class that method applies. So here I will now define the same thing explicitly and make sure that the SendToBlog method specifies to what it belongs.

public class PostContent
{
    void IBloggable.SendToBlog()
    {
        // Send to blog only for the interface not for implementing classes
    }
}

As Joydip pointed out so well, the first one will work in either of these circumstances, but our explicitly defined method will only work in the first example.

Example 1:

IBloggable b = new PostContent();

Example 2:

PostContent b = new PostContent();

From this we can note a couple of other interesting points here.

If we implement interface methods implicitly, we are able to use the method with objects of the interface type or of the implementing class type. If we are implementing explicitly, the method will only work on the interface. The great benefit of only allowing instances of the interface to use the method is that it encourages you to write more dynamic and maintainable code since you'll be using the interface everywhere you'll be able to switch your implementing classes quickly and easily.

This is one of many great ways to write better code. I always explicitly implement my interfaces. I've not had it bite me yet, so if anyone knows a reason to not explicitly define this code, please let me know.

One nice feature in Visual Studio which makes this nice and easy. Once you specify the interface you want your class to implement you are able to right click on it and choose Implement Interface > Implement Interface Explicitly and it will create the stubs for everything required in order to implement the interface. It will even place it all in a nice code region for you. Observe the code it generates for us in this instance.

public class PostContent : IBloggable
{
    #region IBloggable Members

    void IBloggable.SendToBlog()
    {
        throw new Exception("The method or operation is not implemented.");
    }

    #endregion
}

Happy coding.

Static Methods and Interfaces in C#

Someone just commented on my C# interfaces article on ASP Alliance asking an interesting question, and I figure I will respond to it here since I can give a better response here. I don't want to clutter the article comments. Also I can add nifty cool pictures, format all of my text nicely, and write a heck of a lot more here.

This is the excellent question I was asked.

All my classes implementing my interface should have a static funtion.
Why can't I have a static function in an interface???

-Jan

This is how I responded in the article.

One important thing to understand about static methods is that they don't really need to be tied to classes. Static methods basically just exist for convenience.
An interface is as the name says an interface to something. Think of it like an automobile interface. There are defined ways of working with the car. They have a steering wheel a gas pedal and brakes. An interface defines that and all automobiles will have those, but an interface doesn't define anything about "cars in general" (static) it defines what will be the interface for individual cars (instances).

As I was saying interfaces are used for defining interfaces for code. I like my car analogy, but I think I'll use a sail boat analogy this time.

Think of writing an interface in C# called ISailable. This objects implementing this interface will be sailboats. So what does every sailboat need to be able to function. For simplicity I'll say that we just need to have sails and a wheel. All sailboats will also need to be able to sail. So now we've defined how our ISailable objects work. We can now create sailboats using this nice interface. Notice we haven't defined how large the sails are or what style of sails. We just said we need sails. We also did not define the wheel. Is it metal or wood? How large is it? We don't care in the interface the classes implementing the interface will each define those differently. Notice that different boats have very different types of sails.

We might define out ISailable interface in the following way. Keep in mind I am using a lot of simplicity here.

namespace Enrick.Interfaces
{
    public interface ISailable
    {
        void Sail(string destination);
        void Steer(string direction);
        void RaiseSails();
        void LowerSails();
    }
}

Then once we have that defined we are able to implement the interface and create our first sailable object which will of course be a sailboat.

namespace Enrick.Boats
{
    public class SailBoat : Enrick.Interfaces.ISailable
    {
        #region ISailable Members

        public void Sail(string destination)
        {
            // Write sailing logic here. It should be specific to this type of boat.
        }

        public void Steer(string direction)
        {
            // Write steering logic here for this exact type of boat.
        }

        public void RaiseSails()
        {
            // Write logic to raise these specific sails here.
        }

        public void LowerSails()
        {
            // Write logic to lower these specific sails here.
        }

        #endregion
    }
}

Static interfaces do not really apply to what we've defined though. We've just been talking about how to interface with individual sail boats. We haven't gotten to static methods really. This is because static methods aren't really necessary. Many languages have them, but they could just as easily be outside of the class and have the same functionality. Static methods are by definition methods which aren't specific to individual instances of classes. This means we could define these methods anywhere and achieve equivalent functionality. They also don't really apply with interfaces and the C# language specification doesn't allow static methods on interfaces because they don't really make sense with interfaces.

There are circumstances where someone might want to have a static method on an interface. Perhaps the static method was going to be a way of performing an action on an entire collection of the instances of the objects. Perhaps you have a fleet of ISailable ships that you will want to sail together. This would make sense to have a static method which would be associated with the class, but it isn't necessary. Instead we will create a static method elsewhere. It will not be tied to our interface. We can have it take a list of ISailable objects and then it can perform the sailing operation of our fleet.

public void SailFleet(List<ISailable> fleet, string direction)
{
    foreach (ISailable boat in fleet)
    {
        boat.Sail(direction);
    }
}

Notice here that I've defined a method which might have been static before on each of the boats and each one would have take a List of their instances, but that would be silly. This solution allows us to have methods which work with ISailable objects but they need not be defined as requiring an interface. Sadly there is not a way of having static methods on interfaces in C#.

I hope that answers some questions. As always, thanks for reading!

An Explanation of Interfaces in C# for Beginners

I recently authored an article for ASP Alliance in which I describe the basics of how interfaces work and how to use and create them in C#. I tried not to describe in great detail exactly how everything works, because that will prevent beginners from understanding how interfaces may be used. I plan to write further about this topic, but I think it a mistake to begin with even an intermediate description of a topic without at least giving a beginners explanation first. I'll be doing some more advanced examples for my next article on interfaces, so look forward to one in the not too distant future.

I am not sure how the rest of you feel, but I think that interfaces are an amazing tool. I try to use interfaces when possible, because it makes code much more maintainable.

Let me know what you think and any suggestions for future articles.

As always, thanks for reading!