Coding Notes

Ideas and thoughts from Seth Long

Inheritance

My blog is now located at http://www.WhoIsSethLong.com

A good friend of mine called me up the other day and said he was getting back into programming after being away from it for many years.  He was having a hard time understand the concept of inheritance and asked me for a really easy to understand example.  So here it is…

The easiest way to understand inheritance is to think about your parents.  Ok, I know you’re wondering what thinking about your parents has to do with programming but let me explain.  You are a unique individual yet you share many of the same features as your parents.  You inherited those features from you parents and combined them with your own features, creating a new and unique individual.  Well, inheritance in programming isn’t much different.  You create a new class that inherits the properties and methods of another class.

For this example, we will have a class named AlcoholicBeverage.  In case you didn’t know, all alcoholic beverages contain alcohol and have a “proof”.  So, we’ll add the properties “Proof” and “AlcoholPercent” to the AlcoholicBeverage class.  This class will act as the “parent” for our future beer and wine classes.

class AlcoholicBeverage
{
    protected double _PercentAlcohol;
    public double Proof
    {
        get { return (_PercentAlcohol * 2); }
        set { _PercentAlcohol = (value / 2); }
    }
    public double PercentAlcohol
    {
        get { return _PercentAlcohol; }
        set { _PercentAlcohol = value; }
    }
}

 

Next, we will create our beer and wine class which will inherit from the AlcoholicBeverage class.  A beer and a glass of wine both have a percentage of alcohol and a proof but we will not need to add them to our beer and wine classes since they are already defined in the base AlcoholicBeverage class.

class Beer : AlcoholicBeverage
{
    public Beer()
    {
        PercentAlcohol = 2.5;
    }
}
 
class Wine : AlcoholicBeverage
{
    public Wine()
    {
        PercentAlcohol = 12;
    }
}

 

Now we can create our new beer and wine classes and check their Proof.

Beer bottleOfBeer = new Beer();
Console.WriteLine(bottleOfBeer.Proof.ToString());
 
Wine glassOfWine = new Wine();
Console.WriteLine(glassOfWine.Proof.ToString());

 

When run, it gives the following output:

5
24

This is a really simple example of inheritance.  Hopefully it’s simple enough for everyone to understand.  Well, that’s all for now!

– Seth Long

Advertisements

May 8, 2008 Posted by | Architecture and Design Patterns | Leave a comment

Coupling and Cohesion

My blog is now located at http://www.WhoIsSethLong.com

One of my biggest pet peeves as a programmer are other programmers who create giant “do all” general classes rather then creating a few smaller specialized classes.  So, I thought it would be a good idea to write a little bit about the Object Oriented principles of Coupling and Cohesion that deal specifically with this issue.

Coupling refers to how tightly different classes are connected to one another.  Tightly coupled classes contain a high number of interactions and dependencies.  Loosely coupled classes are the opposite in that their dependencies on one another are kept to a minimum and instead rely on the well defined public interfaces of each other

Ok, I know it’s hard to understand coupling if you’ve never heard about it before, so I think the best way to explain it is with an example.  I read a great description of coupling a while back that I’m going to share here.  I think it will really help people better understand the concept of coupling.  It was in a reply post on the Sun Developer’s Network forums and just does a great job of describing coupling in easy to understand terms.

Legos, the toys that SNAP together would be considered loosely coupled because you can just snap the pieces together and build whatever system you want to. However, a jigsaw puzzle has pieces that are TIGHTLY coupled. You can’t take a piece from one jigsaw puzzle (system) and snap it into a different puzzle, because the system (puzzle) is very dependent on the very specific pieces that were built specific to that particular “design”. The legos are built in a more generic fashion so that they can be used in your Lego House, or in my Lego Alien Man. 

The code example below shows two very simple classes that are tightly coupled to one another.  It was inspired by actual code from the Ektron CMS my previous employer so dearly loved.  It is not the actual code but is in the exact same format.

class TightCoupling
{
    public void ShowWelcomeMsg(string type)
    {
        switch (type)
        {
            case “GM”:
                Console.WriteLine(“Good Morning”);
                break;
            case “GE”:
                Console.WriteLine(“Good Evening”);
                break;
            case “GN”:
                Console.WriteLine(“Good Night”);
                break;
        }
    }
}
class TightCoupling2
{
    public TightCoupling2()
    {
        TightCoupling example = new TightCoupling();
        example.ShowWelcomeMsg(“GE”);
    }
}

In the above example, the ShowWelcomeMsg function can not be called without knowing the inner-workings of that function making it nearly useless for other systems.  Secondly, if another developer in the future decides to change the switch statement in the ShowWelcomeMsg function, it could inadvertently effect other classes that call that function.

It shouldn’t be too hard to see that loosely coupled classes offer much greater code reuse and flexibility then tightly coupled classes.  Any changes to tightly coupled classes run the high risk of inadvertently effecting other classes and their dependence on other specific classes making them worthless outside the system they are in.  With loosely coupled classes we use well defined public interfaces.  This give us the flexibility to modify the internals of the class in the future without effecting other classes and allow us to reuse the code in other systems.  So, next time you are writing a class, think to yourself: Am I writing a Lego or am I writing a puzzle piece?

Cohesion is often mentioned with Coupling since they usually go hand-in-hand.  Cohesion refers to how closely related methods and class level variables are in a class.  A class with high cohesion would be one where all the methods and class level variables are used together to accomplish a specific task.  On the other end, a class with low cohesion is one where functions are randomly inserted into a class and used to accomplish a variety of different tasks.  Generally tight coupling gives low cohesion and loose coupling gives high cohesion.

The code below is of an EmailMessage class that has high cohesion.  All of the methods and class level variables are very closely related and work together to accomplish a single task.

class EmailMessage
{
    private string sendTo;
    private string subject;
    private string message;
    public EmailMessage(string to, string subject, string message)
    {
        this.sendTo = to;
        this.subject = subject;
        this.message = message;
    }
    public void SendMessage()
    {
        // send message using sendTo, subject and message
    }
}

Now here is an example of the same class but this time as a low cohesive class.  This class was originally designed to send an email message but sometime in the future the user needed to be logged in to send an email so the Login method was added to the EmailMessage class.

class EmailMessage
{
    private string sendTo;
    private string subject;
    private string message;
    private string username;
    public EmailMessage(string to, string subject, string message)
    {
        this.sendTo = to;
        this.subject = subject;
        this.message = message;
    }
    public void SendMessage()
    {
        // send message using sendTo, subject and message
    }
    public void Login(string username, string password)
    {
        this.username = username;
        // code to login
    }
}

The Login method and username class variable really have nothing to do with the EmailMessage class and its main purpose.  This class now has low cohesion and is probably not a good example to follow.

So that’s a brief overview of Coupling and Cohesion.  Remember, if you want easy to maintain and reusable code, stick to loose coupling and high cohesion in your objects.  I should also mention that there are times where tight coupling is desirable but it’s rare that I’ll leave that up to you to read more about on your own.  Also, I really recommend reading up on Cohesion and Coupling on Wikipedia.  They have a lot more detail and information there then what I’ve written here.

– Seth Long

February 14, 2008 Posted by | Architecture and Design Patterns | 2 Comments