Monday, June 30, 2014

Interfaces: Better Design, How & When to Use

An interface contains only the signatures of methods, properties, events or indexers = like a list of WHAT needs to be done by everything that implements (claims) the interface. The interface itself is only allowed to list them! Not use, define, or implement them on its own!

A class or struct that implements the interface must implement the members of the interface = takes that list of WHAT and shows you exactly HOW by defining the actual methods, properties, events or indexers. Showing is doing!

The typical naming convention is to put the letter "I" before the name of the interface. Let's say I have an interface for recipes! I will call on what it is, define a name with the letter "I" before.. and have it return void (return void means don't return anything). This is a sample of where I have a set of recipes that should be findable and listable on a website! Note how the two things I want it to do will be split into the interface and class files. First is the interface:

namespace Fitness.DAL
{
    // Notice how below I only listed WHAT we will do, but nothing about HOW!
    public interface IRecipeDAL
    {
        // WHAT #1 to find recipes
        Recipe FindRecipeByID(int id);

        // WHAT #2 to list recipes
        IList FindAllRecipes();

    }
}

Here is the class:

namespace Fitness.DAL
{
    // Here we are implementing the interface by calling the IRecipeDAL
    public class RecipeDAL : IRecipeDAL
    {
        // WHAT #1 to find recipes has a HOW below. It tells it where in the database to go and to get the id! 
        private FitnessEntities db = new FitnessEntities();
        public Recipe FindRecipeByID(int id)
        {
            Recipe recipe = db.Recipes.Find(id);
            return recipe;
        }

        // WHAT #2 to list recipes also has a HOW below.  This one says to return a list of the recipes from the database.
        public IList FindAllRecipes()
        {
            return (db.Recipes.ToList());

        }
    }
}

We use interfaces in order to make things easy to edit and change in the future! It makes less work for us now, less work for us later.. and the only thing it requires is a little planning ahead! You want to always keep all of your pieces separate from one another.. individual working parts that can be interchanged. We would be quite upset if for example someone fused your engine to your gas tank and your steering wheel.. and you had to take apart all of those if one went out or was upgraded. So the same applies here, you keep the parts neat and within the bounds of their function and then use interfaces to link the pieces together. A class can have none, one, or many interfaces. Interfaces are an integral part of good design for architecture that is easy to use and modify for the future (be nice to fellow future selves and other developers!).