Guess Whos Back

Hi there! I haven’t seen you in awhile..does it hurt to drop by and visit your dear old uncle Average Programmer now and then?!

Okay okay maybe it my fault for not posting in awhile...let’s not assign blame here. I’ve been busy with a lot of stuff lately, mainly gaming and personal projects, but I hope to get back into the blog posting flow soon.

And who knows, maybe you’ll see some posts about these personal projects soon. But I digress, starting next week I’ll be moving back to the 2 week post schedule. Hopefully this time around I’ll stick to it.

Solid - Dependency Inversion principle

It’s time for the Solid series finale! Are you ready for the D?!!!!!!!

Dependency inversion principle (DIP) that is. Which is the last letter in SOLID acronym. DIP is special among the other principles in that you probably already unconsciously learned it while we were taking our Solid journey together. In fact once I describe DIP you’ll probably just close the tab and go back to watching educational videos since you’ll find you already know principle. I know that's all I do on the internet.


The Dependency inversion principle definition has two components to it.

  1. High-level modules should not depend on low-level modules, both should depend on abstraction.
  2. Abstractions should not depend on details, details should depend on abstractions.


So basically always put a layer of abstraction (interface, abstract class, etc) between two modules when possible. Why? To battle a developer’s mortal enemy, change! We all know change is evil but when it occurs having a layer of abstraction to blunt its impact helps save time and improves code cleanliness.

Let’s head to an example.

Code Example

First let’s pick what we want our high level module to represent...how about a Fish? Fish are said to be one of the most intelligent animals on the planet. Well I said it...just now. Anyway say we want to represent a Fish's ability to fly. We could implement a low-level module Fly class and just have the Fish class make use of it.

        public class Fish
        {
            public void Swim(){}
            public void Eat(){}
            public void Fly(Fly fly){}
        }

        public class Fly
        {
            public void Fly(){}
        }

The code looks fine right (Just nod your head)? But in reality this code is very problematic. First of all not all Fish fly. If the only fish that will make sure of this subclass is the Exocoediate fish, what’s the point of making every fish use the Fly class? Plus if an ichthyologist discovers even more fish that can fly later on, the Fly class would end up bloated in an effort to contain all the logic since it is possible that these fish could fly in very different ways.

We can instead make create a Fly interface (An Abstraction) which the Fish class can depend on.

        public interface IFly
        {
           void Fly();
        }

And we can add details (aka implement the interface) which depend on the Fly interface.

        public class Fish
        {
            public void Swim(){}
            public void Eat(){}
        }

        public interface IFly
        {
            void Fly();
        }
      
        public class FlyingFish : Fish, IFly
        {
            public void Fly()
            {
                Console.WriteLine("I'm a fish that is flying.");
            }
        }

So do you know how to DIP? Good, I’ll be skipping the coding problem this time since if you’ve been following the series you probably already have DIP down easy. Let me know in the comments if you don’t (when I release the commenting system...it’s coming soon!) and I’ll update this post later.

Whew, so that's it. Wow, I can’t believe we made it all the way through. My first blog post series is finally complete. WHAT MEANING IS THERE LEFT IN MY LIFE?! Well I guess I’ll just proceed to the next topic (I’ll try and surprise you). Thanks for reading!

Solid - The Interface Segregation Principle

Welcome! We are now on the letter i which stands for the interface segregation principle or ISP (I don’t want cable bundled with my internet Comcast!).

Source: Top Game


The interface segregation principle states that no client should be forced to depend on methods it doesn’t use. This principle is pretty self explanatory. If a interface is never going to use a particular inherited method, what's the point of even referencing that method? It's kind of like declaring a variable and then never using that variable anywhere in the program. Not following the ISP will lead to code that is tightly coupled which will make future code changes and maintenance a huge pain. And we like to avoid pain at all cost! Unless of course you’re into that sort of thing...which is cool, this is a judgement free zone friend.

*Ahem* Let’s look at an example


Code Example

Imagine we were writing some sort of pencil software program. If we had to make sure that this software would work with a variety of pencils, we might think to create a pencil interface.

    public interface IPencil
    {
      void Sharpen();
      string Draw();
      void Erase();
    }

The interface looks pretty solid (no pun intended), but what if we wanted to add support for mechanical pencils? We might create another interface that represents a mechanical pencil.

    public interface IMechanicalPencil : IPencil
    {
      void RefillLead();
    }

The main difference between a mechanical pencil and a normal pencil is refillable lead, which we captured in the interface above. But since a mechanical pencil never needs to be sharpen, it will never make use of the Sharpen method it inherits. So in order to respect the ISP we might attempt to make the sharpening method its own interface.

    public interface ISharpen
    {
      void Sharpen();
    }

This means anyone can implement ISharpen whenever they need it. It also gives us the added bonus of the Mechanical pencil only inheriting methods it actually uses.

Ready to test your knowledge of ISP? It’s coding problem time.

Coding Problem

So you’ve just joined a software company that produces software for mp3 players and are looking to expand the software to support other mp3 players on the market. Luckily they hired you for the sole purpose of just architecting the interface’s the software program will be using...suckers. The source code is currently the following:

        public interface IMp3
        {
            void PlayMusic();
            void PlayVideos();
            void PlayPodcasts();
            void ViewEbooks();
        }

Since a big mp3 player conference called “BUY A FREAKIN MP3 PLAYER” is coming up in a few weeks you have to add the following features.

1. Make it support the Ipod Shuffle. The Ipod Shuffle can only play music.

2. Make it support the Zune. The Zune can play music, videos, and podcasts.

3. Make it support the Sandisk Clip Sport. The Sandisk Clip Sport can play music and videos.

4. Make it support the Ipod Touch. The Ipod touch can play music, videos, podcasts, and can view documents.

So how’d your solution turn out? Well compare it to the one below and let me know! We only have one letter left in Solid and it's a big one!

C# Solution

        public interface IPlayVideos
        {
            void PlayVideos();
        }

        public interface IPlayPodcasts
        {
            void PlayPodcasts();
        }

        public interface IViewEbooks
        {
            void ViewEbooks();
        }

        public interface IMp3
        {
            void PlayMusic();
        }

        public interface IIpodShuffle : IMp3
        {
            void SpecialShuffle();
        }

        public interface IZune : IMp3, IPlayVideos, IPlayPodcasts
        {
            void ActivateBigHardDrive();
        }

        public interface ISandiskClipSport : IMp3, IPlayVideos
        {
            void TurnOnSportMode();
        }

        public interface IIpodTouch : IMp3, IPlayVideos, IPlayPodcasts, IViewEbooks
        {
            void ActivateDRM();
        }

Solid - The Liskov Substitution Principle

It’s time once again to venture into the world of Solid.

The next letter in Solid is L which stands for the Liskov substitution principle (LSP). The formal definition of the Liskov substitution principle as copied from Wikipedia is the following: “Let F(x) be a property provable about objects x of type T. Then F(y) should be true for objects y of type S where S is a subtype of T.” WAIT! Don’t let those eyes glaze over just yet! The principle is basically saying that if S is a subtype of T then objects of type T can be replaced with objects of type S anywhere in the program. For example if I have a Bear which is a subtype of an Animal then an Animal should be able to do everything a Bear can do. You know, eat honey and bother Ranger Smith.

I think this one of the Solid principles that people use the most even without being aware of it. In fact many programming languages have actually built in some standard signature and behavioral requirements derived from the LSP into their respective languages. This alone speaks to its benefits.


So how do you know if you’re following the LSP? Well just remember that the class subtyping must support all possible behavior the superclass exhibits. Most of the time this is easy to see once you start implementing a classes methods and properties.

Let’s walk through two examples

Code Example

Say you have an Animal class and decide to make a Cat class which inherits from it. Does this violate the LSP? Well conceptually it's seems fine since if you told a crowd a people that Cats are animals, they would all agree with you. Well…you probably would get one gun shoot wound from the Cat Lady in the room.

Anyway our Animal class may look something like this.

       public class Animal
       {
           public virtual void Eat(string food)
           {
               Console.WriteLine("Nom Nom Nom.");
           }

           public virtual void Drink(string water)
           {
               Console.WriteLine("Slurrrrrp.");
           }
       }

Not a bad looking class if I say so myself but it’s unfortunately not enough to tell if us if a LSP violation will occur. So let’s create our Cat class!

       public class Cat : Animal
       {
           public override void Eat (string food)
           {
               Console.WriteLine("Plays with it for half a hour.");
               Console.WriteLine("Chew chew chew.");
           }

           public override void Drink(string water)
           {
               Console.WriteLine("Stare at water.");
               Console.WriteLine("Walk away.");
           }
       }

Well since all the methods are easily supported, the LSP seems to be intact!

Now let’s look at a Rectangle class. If we make a Square subtype is the LSP violated? Well conceptually that seems like a fine idea. After all if you were taking a math test and one of the questions asked if a Square was a Rectangle, wouldn’t you write yes? Nah who are we kidding, we all know you suck at math.

Let’s declare our Rectangle class.

   public class Rectangle
   {
     public int Length;
     public int Width;

     public virtual int Area()
     {
       return Length* Width;
     }

     public virtual void AdjustWidth(int width)
     {
       Width = width;
     }
   }

Nothing out of the ordinary so far, lets create our Square class.

   public class Square : Rectangle
   {
     public override int Area()
     {
       return Length * Length;
     }

     //Uhhhhh wait, aren't the width and length always supposed to be equal for a square?
     public override void AdjustWidth(int width)
     {
       Width = width;
     }
   }

Uh-oh, ran into a little problem. Since all sides of a square have to be equal, we can’t set the width individually. We can fix this by also setting the length, but then our method name would be a lie. It just seems like I can’t substitute a Rectangle for a Square, which violates the LSP. It’s time for a refactor.

Got the LSP down? Good. We’re going to deviate from the normal format and skip the Coding Problem. I find that the LSP is more of a preventative measure and existing code extensibility check. So instead doing a small code problem, take some time to examine some code in which you’re subtyping. Are you following the LSP? If not maybe it's time for a refactor.

Thanks for reading!

Solid - The Open Closed Principle

Welcome back.

It’s time to continue our journey on the SOLID highway! So strap yourself in because there are cops behind us and there’s no way I’m going back to jail. Our next stop is the letter O which stands for the Open Closed Principle. We’ve already discussed the benefits of SOLID as a whole in a previous blog post, but I think the Open Closed Principle makes it a little more apparent how much programming for extensibility benefits you.


The Open Closed Principle states that classes, methods, and modules in general should be open for extension, but closed for modification. So does that mean that I never have to modify existing code again?! This could mean that I never have to learn a legacy system ever again, I can just extend everything! Suck it Michael Feathers. Well…it turns out that’s not quite what the principle is striving for. It also turns out that Mr. Feathers can throw a mean right hook.


You’ll never be able to get away from modifying code you’ve already written, and I don’t think you would ever want to. After all as a programmer you’ll find yourself improving and learning something new everyday. And a day will come when you can’t resist fixing up some embarrassing code you wrote in the past and changing the commit logs so no one can trace it back to you. The Open Closed Principle is more about identifying where change will occur and coding it in a way that lends itself to extensibility. This in turn will lead to less code modification. If you ever found yourself thinking “I only came in here to change one thing, why do I have to change all this other crap?!”, this principle was made for you.

Let’s head to an example.

Code Example

Let’s pretend we have to implement some email based logging. When an error occurs somewhere in the code base we have to fire off an email to a central bug email address. Our code could look something like this:

        public void AttemptToFindCar(Car car)
        {
            try
            {
                car.FindCar();
            }
            catch (Exception e)
            {
                MailMessage mail = new MailMessage("");
                SmtpClient client = new SmtpClient();
                client.Port = 25;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Host = "smtp.google.com";
                mail.Subject = "An Error Occurred when attempting to find car.";
                mail.Body = "Dude where's my car? Exception: " + e;
                client.Send(mail);
            }

        }

Imagine similar try catch’s scattered throughout the codebase. If we suddenly decide to switch to using something like GrayLog, how much of a pain would it be to swap out all the email logging code? If we followed the Open Closed Principle we would have first identified that logging could change in the future and then we would have wrap a interface around it. So in the end it would look something like this:

        public void AttemptToFindCar(Car car)
        {
            try
            {
                car.FindCar();
            }
            catch (Exception e)
            {
                Logger Log = new EmailLogger();
                Log.LogMessage(e.Message);
            }

        }


        public interface Logger
        {
            public void LogMessage(string message);
        }

        public class EmailLogger : Logger
        {
            public void LogMessage(string message)
            {
                MailMessage mail = new MailMessage("");
                SmtpClient client = new SmtpClient();
                client.Port = 25;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Host = "smtp.google.com";
                mail.Subject = "An Error Occurred when attempting to find car.";
                mail.Body = "Dude where's my car? Exception: " + message;
                client.Send(mail);
            }
        }

All we would have to do is make a new GrayLogLogger and then use that instead of the Email based one. So think you have a firm grip on the Open Closed Principle? ARE YOU DOWN WITH OCP? Yeah you know me!...lets do a coding problem.

Coding Problem

Let’s say you just joined a startup that is selling a revolutionary pet feed dispenser. Because it's sporting the latest in food technology, it contains the ability to dispense brand exclusive pet feed to variety of household pets. The dispenser also makes use of dna technology which helps it correctly dispense the correct food depending on which animal touches the feed dispenser. Currently the dispenser only supports dog’s and its source code looks something like this:

        public enum Touch
        {
            DogTouch
        }

        public class PetFeedDispenser
        {
            int usesUntilDispenserFailsForNoReason = 2000;

            public void DispensePetFeed(Touch touch)
            {
                if (usesUntilDispenserFailsForNoReason > 0)
                {
                    usesUntilDispenserFailsForNoReason--;
                    Console.WriteLine("Here's some dog food!");
                }
            }
        }

        static void Main(string[] args)
        {
            PetFeedDispenser dispenser = new PetFeedDispenser();
            dispenser.DispensePetFeed(Touch.DogTouch);
        }

The static main method is where our fake pets will be touching the pet feed dispenser. Account for the following numbered items. Be sure to mentally record how much code you have to change to account for each item.

1. Marketing has just determined that Cat’s are hot right now. So you must now add support for them (feel free to just write some cat food text out to the console).

2. Your CFO just got a pet raccoon! Raccoon support must be implemented by the end of the day. Luckily they eat dog food!

3. You secretly got a rabbit over the weekend. You decide to add in rabbit support. They of course eat carrots.

4. Lastly you have to support Honey Badgers. They eat beehives because they just don't give a...fark.

C# Solution

        public enum Touch
        {
            DogTouch,
            CatTouch,
            RaccoonTouch,
            RabbitTouch,
            HoneyBadgerTouch
        }

        public interface IFeedDispenser
        {
            void DispensePetFeed();
        }

        public class DogFeedDispenser : IFeedDispenser
        {
            public void DispensePetFeed()
            {
                Console.WriteLine("Here's some dog food!");
            }
        }

        public class CatFeedDispenser : IFeedDispenser
        {
            public void DispensePetFeed()
            {
                Console.WriteLine("Here's some cat food!");
            }
        }

        public class RabbitFeedDispenser : IFeedDispenser
        {
            public void DispensePetFeed()
            {
                Console.WriteLine("Here's some carrots!");
            }
        }

        public class HoneyBadgerFeedDispenser : IFeedDispenser
        {
            public void DispensePetFeed()
            {
                Console.WriteLine("Here's some beehives!");
            }
        }

        public class PetFeedDispenser
        {
            int usesUntilDispenserFailsForNoReason = 2000;

            public void DispensePetFeed(Touch touch)
            {
                if (usesUntilDispenserFailsForNoReason > 0)
                {
                    usesUntilDispenserFailsForNoReason--;
                    switch (touch)
                    {
                        case Touch.RaccoonTouch:
                        case Touch.DogTouch:
                        {
                                var dispenser = new DogFeedDispenser();
                                dispenser.DispensePetFeed();
                                break;
                        }
                        case Touch.CatTouch:
                        {
                                var dispenser = new CatFeedDispenser();
                                dispenser.DispensePetFeed();
                                break;
                        }
                        case Touch.RabbitTouch:
                        {
                                var dispenser = new RabbitFeedDispenser();
                                dispenser.DispensePetFeed();
                                break;
                        }
                        case Touch.HoneyBadgerTouch:
                        {
                                var dispenser = new HoneyBadgerFeedDispenser();
                                dispenser.DispensePetFeed();
                                break;
                        }
                        default:
                            Console.WriteLine("I don't recongize this animal. Self destruct initiated.");
                            break;
                    }
                }
            }
        }



        static void Main(string[] args)
        {
            PetFeedDispenser dispenser = new PetFeedDispenser();
            dispenser.DispensePetFeed(Touch.DogTouch);
            dispenser.DispensePetFeed(Touch.RaccoonTouch);
            dispenser.DispensePetFeed(Touch.RabbitTouch);
            dispenser.DispensePetFeed(Touch.HoneyBadgerTouch);
        }

Remember to toss me a email if you coded a solution in another language. Thanks for reading!