Blog

Thoughts from the coaches

I recently introduced a new blog series that I am starting aimed at helping beginners understand software patterns.  If you didn’t catch that post, you can read it here.  The first pattern I want to tackle is the factory pattern.  There are lots of great articles out there discussing these patterns in depth, but I want to take a different approach to them.  I want to look at them from a simple perspective.

When you think of a factory, what comes to mind?  In my mind’s eye, I see images of big brick buildings billowing out clouds of dark smoke all with the purpose of producing thousands and thousands of widgets.  The factory pattern is much like the brick building of my imagination in that it has only one purpose.  Its sole responsibility is to create objects.

The idea behind the factory pattern is pretty simple.  You have some code that needs some other code as a dependency.  There may be multiple objects that could satisfy the needs of your code depending on the circumstance.  You program your dependent code to utilize an interface rather than creating a new object.  You then write classes that implement the interface.

Let’s create a very simple example to illustrate the point.  Let’s create a simple console application that has only a line of code to write the phrase Hello World out to the console and another to pause execution until we hit enter.

using System;

namespace FactoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
    }
}

Now suppose we want to be able to change the greeting based on some criteria. Instead of writing Hello World, we want our greeting to be written out by an object that specializes in the type of greeting we need. To do this, we need to write a class that returns the greeting to write.

using System;

namespace FactoryExample
{
    class MorningGreeting
    {
        public string GetGreeting()
        {
            return "Good Morning!";
        }
    }
}

We also have to modify our Program.cs class to use the new object for our greeting.

using System;

namespace FactoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MorningGreeting greeting = new MorningGreeting();
            Console.WriteLine(greeting.GetGreeting());
            Console.ReadLine();
        }
    }
}

If you notice above, we instantiate the MorningGreeting object and then use it to get the message that we want to display. The problem is that we are now tightly coupled between our MorningGreeting class and the code that calls it. We don’t want the application to display “Good Morning” all day long. We want to use something different depending on the time of day. We need another class to display “Good Afternoon” to the user when it is past 12 pm. Let’s write that class.

using System;

namespace FactoryExample
{
    class AfternoonGreeting
    {
        public string GetGreeting()
        {
            return "Good Afternoon!";
        }
    }
}

We now have an issue though. In order to use the AfternoonGreeting class the way it is setup in our Program.cs class, we would have to modify the line of code that instantiates our greeting object and then recompile our application. This simply isn’t feasible. We need to have a way to “de-couple” our code and select which object should be used in a given circumstance. To do this, we need to create an Interface. Interfaces allow us to write similar classes that provide the same methods (with the same parameters and return types) in different classes that can then be used interchangeably. Let’s create an interface that would allow us to do this with our greeting classes.

using System;

namespace FactoryExample
{
    interface IGreeting
    {
        string GetGreeting();
    }
}

We then have to modify each of our greeting classes to implement the interface. We do this by using a colon and the name of the interface following the class declaration.

using System;

namespace FactoryExample
{
    class MorningGreeting : IGreeting
    {
        public string GetGreeting()
        {
            return "Good Morning!";
        }
    }
}
using System;

namespace FactoryExample
{
    class AfternoonGreeting : IGreeting
    {
        public string GetGreeting()
        {
            return "Good Afternoon!";
        }
    }
}

Now we can go back to our Program.cs class and modify it to use the IGreeting interface instead of a concrete class as it’s greeting variable type. This will allow for any class that implements the IGreeting interface to be used there.

using System;

namespace FactoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            IGreeting greeting = new MorningGreeting();
            Console.WriteLine(greeting.GetGreeting());
            Console.ReadLine();
        }
    }
}

There is still a problem though. We created the interface to allow us to use any class that implements that interface to be used. We also coded our logic to use the interface rather than a concrete implementation by specifying the type of our greeting variable to be IGreeting. We are still instantiating a concrete implementation though by specifying that the greeting variable is = new MorningGreeting. We want to let the system choose which object to use based on the time of day. This is where our factory comes in. To create our factory, let’s add another class. I’m going to make this one static.

using System;

namespace FactoryExample
{
    static class GreetingFactory
    {
        public static IGreeting CreateGreeting()
        {
            DateTime noon = Convert.ToDateTime("12:00:00 PM");
            DateTime now = DateTime.Now;

            if (now < noon)
            {
                return new MorningGreeting();
            }
            return new AfternoonGreeting();
        }
    }
}

This gives us a class and method that allow us to get the correct object based on some criteria. In our case is it morning or afternoon. We now only need to modify our Program.cs class one more time to use the factory to give us whichever object is appropriate.

using System;

namespace FactoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            IGreeting greeting = GreetingFactory.CreateGreeting();
            Console.WriteLine(greeting.GetGreeting());
            Console.ReadLine();
        }
    }
}

That should do it. If we run our application at different times of day you should find that the greeting changes depending on whether it is before or after noon. There are easier ways to accomplish what we just did, but think about how this pattern could be used for more complex scenarios. Maybe an insurance company needs to implement a set of rules for calculating a rate based on which state they are selling a policy in. We could create and return the proper rate engine object for the state. Anytime you may want to switch which implementation of an object you need at runtime based on specific criteria, a factory is a reasonable choice to consider.

Modern applications use fewer factories and rely more on dependency injection (DI) for this type of functionality, but understanding factories is a great step toward understanding how DI works.

As an instructor, I am asked from time to time to explain what patterns are.  It seems to be one of those things that new developers often hear dissertations on from the hallowed halls of software architecture then walk away more confused than when they started.  There are vehement opinions on which patterns are the cream rising to the top and which are nothing more than an incessant scourge on our profession.

For someone just learning the craft of software development, the basic syntax and structure of their chosen language can be enough to understand without trying to digest the purpose of a set of patterns.  I usually start to explain patterns by telling my apprentices what they are not.

Patterns are NOT:

  • A magic bullet by which all software development is miraculously completed in record time.
  • A way to ensure that your code will be free of defects.
  • A one size fits all approach to development.

In my time as a professional developer, I often have seen newcomers discover a pattern and glom to it. They become evangelists and bow at the altar of the pattern.  It often becomes an expectation on their part that every problem they are presented with can and must somehow be shoehorned into this new way of doing things.  This is a danger that must be avoided.

What Patterns Are

Patterns are simply a way to write and organize your code as repeatable/reusable segments that solve specific problems.  Did you catch that?  The problems that patterns solve are specific.  This means that any given pattern is not one size fits all approach.  When you run across a specific problem and you solve that problem in a way that allows you to reuse your code to effectively and efficiently solve that same problem again next time, then you have created a pattern.

That’s another point about patterns.  We can write our own patterns.  Becoming effective as software developers means we need to have a box full of tools to use to solve problems more quickly.  Patterns are among the tools that should be in there.  When we discover a pattern in our development, we should hold onto it for future use. That said, there are also a large number of existing patterns that have become prominent within the industry.  It will benefit you to learn about them and the problems they solve.  I am going to start a series of posts exploring some of the more popular patterns, explain their purpose, and provide some examples of their usage.

Learning about patterns is a valuable undertaking, but if you are new to the field you should first master the basics.

 

DevCoaches is hosting another educational event.

What:

Learn to Build Android and iOS Apps with HTML, CSS, and Javascript

Are you a beginner to intermediate level web developer? Join us for a free 4 part workshop where we’ll learn to build Android and iOS applications using the HTML, CSS, and javascript skills you already have.

You’ll learn step-by-step how to build and design a web application using a popular javascript client framework called Framework7. This web application can then be deployed to the web, Android, and iOS all in one. If you learn how to build applications this way you won’t have to spend time building three separate apps ever again. Why would you?

Framework7 – is a free and open source mobile HTML framework to develop hybrid mobile apps or web apps with iOS & Android native look and feel. It doesn’t use and does not depend on any third party libraries and can be integrated (with some work) with almost any existing web-based platform.

When:  August 16, 2017
Where:  The Software Guild, 526 South Main St., Suite 609, Akron, Ohio  44311
Who:  Pat Toner

RSVP:  https://www.meetup.com/TSG-Akron/events/241982200/

Thank you to our sponsor, The Software Guild

 

DevCoaches own Sarah (sadukie)Dutkiewicz has written a really cool parody called Come Write the Code inspired by the song Come Sail Away by Styx.  Check it out on sadukie’s blog.

We recently completed our first DevCoaches workshop. Randall Clapper, Phil Williams, and Victor Pudelski all came together to organize and run the DevCoaches JavaScript Workshop.

It was a great event and has reaffirmed our decision to continue doing more these. We are in the planning phase for a number of additional events in the coming months. Keep an eye on the DevCoaches blog for a definitive schedule of workshops that interest you. Some of the topics we will be covering include:

  • ASP.Net WebAPI
  • Angular
  • ES6
  • TypeScript
  • Electron
  • Entity Framework
  • .Net Core

 

We want to thank The Software Guild in Akron, Ohio for sponsoring and hosting us.

 

More than Just a Podcast

Podcasting may be where we started, but Dev Coaches is much more than just that.  We enjoy getting behind the microphone to share our collective experiences in the software development industry, explore new technology topics, and  offer insights on soft-skills to help our listeners grow in their careers.  We will continue to record and share our thoughts with you as long as you continue to listen, but we feel there is so much more that we can offer as coaches as well.

 


aspnetcore-1

31 Days of .Net Core

One of the initiatives we are working on is a new blog post series exploring the newly released .Net Core.  This series will explore the technology from learning to install and configure the framework and tools, uncovering some of the new and changing features, to building useful applications. We will cover the cross-platform capabilities of core and show you how to develop on windows, mac and linux with Core.  This blog series will be titled 31 days of .Net Core.  Look for the first posts to come in the near future.

 


transfer_workshop_allg

DevCoaches Workshops

We love being involved in the development community and we love teaching people about technology.  To combine our passions and experience in this area, we have decided to organize a series of workshops to help aspiring software developers and industry veterans alike to come together to learn new things.  Our first workshop we are working on will be called “Core Junction” and will feature a day long class to learn how to build a fully functioning application using .Net Core. No Experience required.  We will post more information about this effort as we progress.

Coaching is about more than just shouting from the sidelines, it’s about helping others master the skills.  That’s what we are all about and that’s why we are looking to expand what we do.  We are excited to start rolling this out in the near future.