Why Interfaces are Important

“The key to understanding interfaces might be to compare them with classes. Classes are objects that have properties and methods that act on those properties. While classes do exhibit some behavioral characteristics (methods), classes are things as opposed to behaviors, and that’s how interfaces come in. Interfaces enable you to define behavioral characteristics, or abilities, and apply those behaviors to classes irrespective of the class hierarchy. For example, say that you have a distribution application in which some of the entities can be serialized. These might include the Customer, Supplier and Invoice classes. Some other classes, such as MaintenanceView and Document,might not be defined as serializable. How would you make only the classes you choose serializable? One obvious way would be to create a base class called something like Serializable. However, that approach has a major drawback. A single inheritance path won’t work because we don’t want all the behaviors of the class to be shared. C# doesn’t support multiple inheritance, so there’s no way to have a given class selectively derive from multiple classes. The answer is interfaces. Interfaces give you the ability to define a set of semantically related methods and properties that selected classes can implement regardless of the class hierarchy.

From a conceptual standpoint, interfaces are contracts between two disparate pieces of code. That is, once an interface is defined and a class is defined as implementing that interface, clients of the class are guaranteed that the class has implemented all methods defined in the interface.”

– C# Interfaces – http://www.brainbell.com/tutors/C_Sharp/Interfaces_a3.htm

SOLID Programming Principles

SOLID programming is a collection of five programming patterns for object-oriented programming and design.  The definition of each of the principles is shown below.

S – Single Responsibility Principle (SRP) – A class should have one, and only one, reason to change.

O – Open/Closed Principle (OSP) – You should be able to extend an classes behavior without modifying it.

L – Liskov Substitution Principle (LSP) – Derived classes must be substitutable for their base classes.

I – Interface Segregation Principle (ISP) – Make fine grained interfaces that are client specific.

D – Dependency Inversion Principle (DIP) – Depend on abstractions, not on concretions.

Single Responsibility Principle (SRP)

This principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.   All its services should be narrowly aligned with that responsibility.

As an example, consider a module that compiles and prints a report. Such a module can be changed for two reasons. First, the content of the report can change. Second, the format of the report can change. These two things change for very different causes; one substantive, and one cosmetic. The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should therefore be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times.

The reason it is important to keep a class focused on a single concern is that it makes the class more robust. Continuing with the foregoing example, if there is a change to the report compilation process, there is greater danger that the printing code will break if it is part of the same class.

Open/Closed Principle (OCP)

This principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have come to associate with “bad” design.  The program becomes fragile, rigid, unpredictable and unreusable. The open/closed principle attacks this in a very straightforward way.  It says that you should design modules that never change.  When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works.

The simplest way to apply OCP is to implement the new functionality on new derived (sub)classes that inherit the original class implementation. Another way is to mediate client access to the original class with an abstract interface, so new functionality can be implemented on new classes that are accessed through the same interface. Both ways create new classes and leave the original implementation untouched.

Liskov Substitution Principle (LSP)

It states that, in a computer program if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substitutes for objects of type T), without altering any of the desirable properties of that program (correctness, task performed, etc.)

Here’s an example of a violation of LSP

        void DrawShape(Shape s)
        {
              if (s.GetType() == typeof(Square))
                      DrawSquare((Square) s);
              else if (s.GetType() == typeof(Circle))
                      DrawCircle((Circle) s);
        }

        void DrawSquare(Square s)
        {

        }

        void DrawCircle(Circle s)
        {

        }

The problem with the DrawShape method is that it must know about every possible derivative of the Shape class, and it must be changed whenever new derivatives of Shape are created. Indeed, many view the structure of this function as anathema to Object Oriented Design.

Here’s a better way to implement the method so that it doesn’t have to know all the different types of shapes that need to be drawn.

    class Program
    {
        static void Main(string[] args)
        {
            DrawShape(new Square());
            DrawShape(new Circle());
        }

        static void DrawShape(IShape s)
        {
            s.Draw();
        }
    }

    public interface IShape
    {
        void Draw();
    }

    public class Square : IShape
    {
        public void Draw() { }
    }

    public class Circle : IShape
    {
        public void Draw() { }
    }

Interface Segregation Principle (ISP)

This principle says that once an interface has become too ‘fat’ it needs to be split into smaller and more specific interfaces so that any clients of the interface will only know about the methods that pertain to them. In a nutshell, no client should be forced to depend on methods it does not use.

Here’s an example of an interface used to describe an automobile.

    public interface IAutomobile
    {
        void StartEngine();

        void ApplyBrakes();

        void StopEngine();

        void DropTailGate();

        void EngageFourWheelDrive();
    }

The problem with this interface is that it has a couple of methods that wouldn’t apply to all automobiles. The DropTailGate and EngageFourWheelDrive methods wouldn’t apply to compact cars or minivans, so a new interface would need to be created for each of these with similar methods related to the engine and breaks.

A better design would have seperate interfaces for the specific features that exist for the different types of automobiles.

    public interface IAutomobile
    {
        void StartEngine();

        void ApplyBrakes();

        void StopEngine();
    }

    public interface ISupportsOffRoadDriving
    {
        void EngageFourWheelDrive();
    }

    public interface ITruck
    {
        void DropTailGate();
    }

The interfaces above prevent the duplication of the engine related methods to the other vehicle types and can be applied in addition to the IAutomobile interface.  For example, a class for Truck would implement the ITruck and IAutomobile interface.  If the truck has four wheel drive options, then it would also implement the ISupportsOffRoadDriving interace.

Dependency Inversion Principle (DIP)

The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

The goal of the dependency inversion principle is to decouple high-level components from low-level components such that reuse with different low-level component implementations becomes possible. This is facilitated by the separation of high-level components and low-level components into separate packages/libraries, where interfaces defining the behavior/services required by the high-level component are owned by, and exist within the high-level component’s package. The implementation of the high-level component’s interface by the low level component requires that the low-level component package depend upon the high-level component for compilation, thus inverting the conventional dependency relationship

Here’s an example of a class that will create an automobile. The Automobile class has a dependency on the Engine class for the TurnIgnitionKey method. The code below is an example of a violation of the DIP principle.

    public class Application
    {
        public void CreateAutomobile()
        {
            var automobile = new Automobile();
        }
    }

    public class Automobile
    {
        Engine _engine;

        public Automobile()
        {
            _engine = new Engine();
        }

        public void TurnIgnitionKey()
        {
            _engine.StartEngine();
        }

    }

    public class Engine
    {
        public void StartEngine()
        {
            // ...
        }

        public void StopEngine()
        {
            // ...
        }
    }

Here’s a better implementation which conforms to the DIJ principle.  All the dependent classes are passed to the constructor of the Automobile class.

    public class Application
    {
        public void CreateAutomobile()
        {
            var automobile = new Automobile(new Engine());
        }
    }

    public class Automobile
    {
        Engine _engine;

        public Automobile(Engine engine)
        {
            _engine = engine;
        }

        public void TurnIgnitionKey()
        {
            _engine.StartEngine();
        }

    }

The example above now enables unit testing with mock objects.  This type of testing isolates testing to specific method behavior.  Any dependencies of the method are mocked which confirms that any test failures are isolated to the specific method being tested and none of it’s dependencies.

Useful links:

http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29

http://blog.symprise.net/2009/06/open-closed-principle-concerns-about-change-in-software-design/

http://www.oodesign.com/dependency-inversion-principle.html

Senior Software Engineer Interview Questions

Scott Hanselman has posted some new questions here that you can use to interview a senior level software engineer.  There’s a lot of good questions and several are ones I need to look up myself :).  I think I may try posting answers to as many of these questions as well as some of the questions he’s listed in an older post.

I also found a link in the comments for 5 essential phone screen questions.  Take a look here when you get a chance.

Using Lamda Expressions as Properties

Found a really cool article describing how lambda expressions can be used as properties.  Here’s a brief description:

The idea is pretty simple.  You define a property, which, instead of returning some scalar value, returns a lambda expression (or pretty much any form on anonymous function).  The property works just like a instance method, except we can assign and change it at run-time.

http://honestillusion.com/blogs/blog_0/archive/2010/06/07/lambda-expressions-as-properties.aspx

UPDATE:   Looks like that link is dead.  Here’s a copy of the original article:

 

Peter recently caused a bit of a stir with his article “Sometimes an enum is not the best idea”.  In it, he had a very specific problem: When an enum is passed to a method as an Object, and that method converts it to a usable value by calling ToString(), you get that enum’s name and not it’s value.  And he gave a gave very specific solution to that problem.  Peter wanted an simple ad hoc solution that he could just drop into his code.  Peter’s idea was basically a quick fix to replace a bad design with something slightly less bad.   The problem arose when readers inferred that it was intended as a far more general solution, and pointed out different, more architectural solutions.  Bickering started in the comments.

I think the main problem is that Peter just want a quick fix to his existing design, and viewed a proper design as overkill for his simple needs.  However, since those simple needs were out of scope of his original purpose for the  article, he never got into specifics.  However, knowing the specifics would be key to knowing how complex the design needs to be.  This was the essence of Peter’s follow-up article (which he posted as I was in the middle of writing this)

So, let’s try looking at this problem to see if we can come up with a better design that still meets the goal of being simple.

In Peter’s design, he has a Suppliers class (which he occasionally refers to as the Company class), which has several instances — one for each supplier.  There is also an enum, PublicIds with one entry for each supplier.  PublicIds was used in two places:  In switch statements, and as a parameter in an ADO.NET statement:

public void DoWithCompany(PublicIds company)
{
    switch (company)
    {
      case PublicIds.Company1:
      // Do something with Company 1
      break;
      case PublicIds.MyCompany:
      // Do something with My Company  
      break;
      case PublicIds.ThatOtherCompany:
      // Do something else
      break;
    }
}

cmdExists.Parameters.AddWithValue(“@idSupplier”, Supplier.PublicIds.MyCompany);

 

The second use was the real motivator of Peter’s article – The first was what caused all the hoopla on the blog.

Commenters proposed some general ideas, basically out of Object-Oriented Design 101 – Creating a new subclass for  each of the Suppliers, with overridden methods.  Peter fought back — the code in the “do something” blocks is not part of Supplier, but is in other classes.  Subclasses would requiring moving non-related code to where it doesn’t belong.

Since Peter still hasn’t provided any real-world examples of his problem (which is reasonable, as they might involve proprietary material or just have too many dependencies to post meaningful excerpts), lets try to imagine some scenarios that might fit his description (namely that DoWithCompany is an example of  a method that “is a member of several quite different other classes and comes in many flavors”).

Ok, so let’s say we have a Order class, with a ProcessOrderToSupplier(Supplier sup) method.   Let’s further say that most of Order processing is the same for all suppliers, but some suppliers offer a discount (or surcharge) under some conditions.  Hence we need custom processing per supplier to handle the discount, but moving order handling into the Supplier class would clearly be wrong.

So, let’s try three different discounting schemes, and come up with three means of handling them in ways that are scalable, maintainable & understandable.

#1 – A flat discount rate on all items.

That’s simple.  A discount rate property (getter only) in Supplier.  It could be an abstract property which is overridden in derived classes (one for each Supplier), or just set in Supplier’s constructor.  (Could be set to zero for those suppliers not offering a discount).

#2 –  Several suppliers offering (free shipping on orders over $100).

The “free shipping blah-blah-blah” part is handled entirely in the Order class.  The Supplier class just needs a way to say whether of not a particular supplier offers it.  This could be handled by a  Property as described above, or an attribute on the derived class, or by a marker interface (a marker interface has no members, and is just used in statements like:

if (sup is IOffersFreeShipping)
     ProcessFreeShipping();

#3 – One supplier offers 10% off total orders over $100. Another offers 15% off individual items over $25. And a third offers a $1 shipping surcharge on items over 20 lb.

Basically,  every supplier offers something different, and each is complex.  We’d think we’d need derived classes with overridden methods here to keep this object-oriented.  But that is exactly “the first step to multiple inheritance or an unmaintainable set of interfaces” which Peter was afraid of.

(My laptop has an interesting way of telling me that I haven’t saved in a while — the battery falls out.  I’ve now – too late — discovered Windows Live Writer’s auto-save feature.  Now let’s see if I can recreate what I just lost……).

And besides that, creating a subclass specifically for one instance of a class just feels wrong — particularly when we would be creating multiple subclass, one for each of several instances.  But how can be package instances of distinct functionality in individual instances of an object.

By using Lambda Expressions as Properties. 

The idea is pretty simple.  We define a property, which, instead of returning some scalar value, returns a lambda expression (or pretty much any form on anonymous function).  The property works just like a instance method, except we can assign and change it at run-time.   If you’ve done any work in JavaScript, you’ve probably seen very much the same thing.

Let’s look at some code.  We start by defining the Supplier class like this:

public class Supplier 
{
    public PublicIds Id {get; private set;}
    public int IdCode {get { return (int) Id;}}
    public Action PerItem {get; private set;}

    public Supplier(PublicIds id, Action perItem)
    {
        Id = id;
        PerItem = perItem;
    }

    public Supplier(PublicIds id) : this(id, oi=> oi=oi)
    {}
}

Note that the constructor takes a Action delegate, and stores it in the PerItem property.

Next, define our instances like this:

Supplier Company1 = new Supplier(PublicIds.Company1);
Supplier MyCompany = new Supplier(PublicIds.MyCompany, oi=> { if (oi.Price > 25m) oi.Discount = oi.Price * 0.15m;});
Supplier ThatOtherCompany = new Supplier(PublicIds.ThatOtherCompany, oi=> {if (oi.Weight >=20) oi.Shipping = 1m;});

And used them  like this:

List items = new List();    
void ProcessOrderToSupplier(Supplier sup)
{
    // :
    items.ForEach(sup.PerItem);
    //:
}

“Ok“, you say. “We’ve got the distinct behavior without subclasses – but we still have order processing code defined outside of the Order class, and to make matters worse, it moved to the instance definition in a really messy way.”

No Problem, we just go back to out (new) old friend: Lambda Expression as Properties:

This time, we’ll create static properties in the Order class:

public class Order
{
    List items = new List();    
    void ProcessOrderToSupplier(Supplier sup)
    {
        // :
        items.ForEach(sup.PerItem);
        //:
    }    

    public static  Action Discount15on25
    {
        get
        {
            return oi => 
                { 
                    if (oi.Price > 25m) 
                        oi.Discount = oi.Price * 0.15m;
                };
        }
    }

    public static  Action Shipping1Over20
    {
        get
        {
            return oi=> 
                {
                    if (oi.Weight >=20) 
                        oi.Shipping = 1m;
                };
        }
    }
}

And we can now define out Supplier instances like this:

 

Supplier Company1 = new Supplier(PublicIds.Company1);
Supplier MyCompany = new Supplier(PublicIds.MyCompany, Order.Discount15on25);
Supplier ThatOtherCompany = new Supplier(PublicIds.ThatOtherCompany, Order.Shipping1Over20);

So, what have we accomplished?

  • We’ve distinct behavior amongst the different suppliers, without resorting to subclasses or switch/case blocks
  • We’ve all the Order processing code in the Order class.
  • We’ve neat & tidy Supplier instance definitions, which nevertheless indicates the special features of that supplier.
  • And we have those special features as part of the Supplier object.

But, wait.  You’re probably saying that those properties we’ve defined on Order are rather specific to one particular trait.  Would it be nice to be able to have one general algorithm which is customizable?  That can be done too, by just extending the general principle, which involves using a method instead of a property, but the basic idea is still the same:  instead of returning a value, we return a function:

public static  Action ShippingByWeight(int pounds, decimal cost)
{
    return oi=> 
        {
            if (oi.Weight >=pounds) 
                oi.Shipping = cost;
        };
}

// :

Supplier ThatOtherCompany = new Supplier(PublicIds.ThatOtherCompany, Order.ShippingByWeight(20,1m);

SQL Server: Loading all the values from a table into a single line (via Tone’s Enterprise Dot Net Blog)

It's a common requirement to load all the values from a table into a single line for consumption. For example, you might retrieve a User record, but you want the list of roles that the user belongs to in a single comma separated line. The usual way of performing this was to create an inline function, pass it the UserId of the record and have it build the list. The problem with that is the inline function – it causes a table scan, which is highly … Read More

via Tone's Enterprise Dot Net Blog