Coding Notes

Ideas and thoughts from Seth Long

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

Advertisements

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

Haversine Formula in C# and in SQL

The Haversine Formula class listed below is used to calculate the distance between two latitude/longitude points in either Kilometers or Miles.  I’ve seen the formula written in a few other languages but didn’t see any in C#.  So, here is the Haversine Formula in C#.  Before I show the class, let me give an example of how the class is called and used.

To start we will need 2 latitude/longitude points.  I created a struct to hold the  latitude/longitude points.  Once we have the points, we create the Haversine class and call the Distance method, passing in the points and an enum specifying whether to return the results in Kilometers or Miles.  We end up with the following:

Position pos1 = new Position();
pos1.Latitude = 40.7486;
pos1.Longitude = -73.9864;
 
Position pos2 = new Position();
pos2.Latitude = 24.7486;
pos2.Longitude = -72.9864;
 
Haversine hv = new Haversine();
double result = hv.Distance(pos1, pos2, DistanceType.Kilometers);

Here is the code for the class:

using System;
 
namespace HaversineFormula
{
    /// <summary>
    /// The distance type to return the results in.
    /// </summary>
    public enum DistanceType { Miles, Kilometers };
 
    /// <summary>
    /// Specifies a Latitude / Longitude point.
    /// </summary>
    public struct Position
    {
        public double Latitude;
        public double Longitude;
    }
 
    class Haversine
    {
        /// <summary>
        /// Returns the distance in miles or kilometers of any two
        /// latitude / longitude points.
        /// </summary>
        /// <param name=”pos1″></param>
        /// <param name=”pos2″></param>
        /// <param name=”type”></param>
        /// <returns></returns>
        public double Distance(Position pos1, Position pos2,DistanceType type)
        {
            double R = (type == DistanceType.Miles) ? 3960 : 6371;
 
            double dLat = this.toRadian(pos2.Latitude – pos1.Latitude);
            double dLon = this.toRadian(pos2.Longitude – pos1.Longitude);
 
            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                Math.Cos(this.toRadian(pos1.Latitude)) *Math.Cos(this.toRadian(pos2.Latitude)) *
                Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
            double d = R * c;
 
            return d;
        }
 
        /// <summary>
        /// Convert to Radians.
        /// </summary>
        /// <param name=”val”></param>
        /// <returns></returns>
        private double toRadian(double val)
        {
            return (Math.PI / 180) * val;
        }
    }
}

 Here is the same formula as a SQL function. I used Microsoft SQL server for this example.

CREATE FUNCTION [dbo].[GetDistance]

(
      @lat1 Float(8),
      @long1 Float(8),
      @lat2 Float(8),
      @long2 Float(8)
)
RETURNS Float(8)
AS
BEGIN
 
      DECLARE @R Float(8);
      DECLARE @dLat Float(8);
      DECLARE @dLon Float(8);
      DECLARE @a Float(8);
      DECLARE @c Float(8);
      DECLARE @d Float(8);
 
      SET @R = 3960;
      SET @dLat = RADIANS(@lat2 – @lat1);
      SET @dLon = RADIANS(@long2 – @long1);
 
      SET @a = SIN(@dLat / 2) * SIN(@dLat / 2) + COS(RADIANS(@lat1))
                        * COS(RADIANS(@lat2)) * SIN(@dLon / 2) *SIN(@dLon / 2);
      SET @c = 2 * ASIN(MIN(SQRT(@a)));
      SET @d = @R * @c;
 
      RETURN @d;
 
END
GO
 

– Seth Long


February 5, 2008 Posted by | Algorithms | 18 Comments

Ternary Search Tree in C#

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

I recently had the urge to create a Ternary Search Tree in C# (doesn’t everyone get these urges?).  My first stop was  at http://www.ddj.com/windows/184410528 for a GREAT article on how Ternary Search Trees work and how to create them.  If you’re really unfamiliar with Ternary Search Trees, I’d recommend starting with the wikipedia article on them before reading this.

For this project, I began by creating a class called TSTree and another called TSNode.  The TSNode class is a very simple class that simply contains properties for the split char, low node, equal node and hi node (later we will add a value).   Here is an example of the TSNode class:

    class TSNode
    {
        private char splitChar;
        private TSNode lowNode;
        private TSNode eqNode;
        private TSNode hiNode;
        private object value;
        public char SplitChar
        {
            get { return this.splitChar; }
            set { this.splitChar = value; }
        }
        public TSNode LowNode
        {
            get { return this.lowNode; }
            set { this.lowNode = value; }
        }
        public TSNode EqNode
        {
            get { return this.eqNode; }
            set { this.eqNode = value; }
        }
        public TSNode HiNode
        {
            get { return this.hiNode; }
            set { this.hiNode = value; }
        }
        public object Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    }

Later on we can add more to the class but for now that is a good start.  So lets briefly go over what it all does. The first property SplitChar holds the char that this node represents. The LowNode holds a reference to a node that holds a SplitChar that is less then the value of this Node, HiNode holds a reference to a node that holds a SplitChar that is greater then the value of this Node and of course EqNode holds a reference to a node that has a SplitChar that is equal.  Pretty much like a binary tree node but with a reference to an equal node added (Binary = 2, Ternary = 3).

The next step is to add an Add method to the TSTree class.  What the Add method is going to do is add a node for each char in a string to the tree.  For example, if we have an empty tree and add the key “cat” to it, it will add nodes for ‘c’, ‘a’, and ‘t’ to the tree.  Since our word is “cat”, the root node will have a SplitChar value of ‘c’.  In it’s EqNode property it will contain a reference to another node with a SplitChar value of ‘a’.  This node will also contain a EqNode reference to another node with a SplitChar value of ‘t’.  So we have three nodes in our tree whos collective SplitChar values spell out “cat”.

Here is the code for the Add method:

        public TSNode Add(TSNode p, string s, int pos, object value)
        {
            if (p == null)
            {
                p = new TSNode();
                p.SplitChar = s[pos];
            }
            if (s[pos] < p.SplitChar)
            {
                p.LowNode = Add(p.LowNode, s, pos, value);
            }
            else if (s[pos] == p.SplitChar)
            {
                if (pos < s.Length – 1)
                {
                    p.EqNode = Add(p.EqNode, s, ++pos, value);
                }
                else
                {
                    p.Value = value;
                }
            }
            else
            {
                p.HiNode = Add(p.HiNode, s, pos, value);
            }
            return p;
        }

Now, when we want to add another word things get interesting.  So, lets add the word “cab” to our tree and see what happens next.  We start by looking at the root node in our tree and see that ‘c’ matches the first letter in our word “cab”.  Since it matches, we follow the EqNode reference and check the next SplitChar value.  In this case it is ‘a’, which again matches the next char in our word “cab”.  Again, we follow the EqNode reference and check the next SplitChar value.  This time, the value of the SplitChar does not equal the last value of our word.  So we have to check if the SplitChar value is greater then or less then the value of ‘b’.  ‘b’ is less then the value of ‘t’ so we will follow the path of the LoNode. In this example the LoNode value is null so we create another node and set its SplitChar value to ‘b’.  That’s how we add items to the tree.

Searching for a string in our tree is going to work a lot like adding an item to it.  If we were searching for the word “cab” in the previous tree we created, we would start by checking the root node’s SplitChar value and compairing it to the value of the first char in our search word.  In this case the ‘c’ in our search word matches the SplitChar value of the root node.  So we follow the reference in the EqNode property to the next node.  The next node contains a SplitChar value of ‘a’ and again matches the second char in our search word of “cab”.  Again, we follow the EqNode reference to the next node and check the SplitChar value.  This time they are not equal so we then determine if ‘b’ is greater then or less then the ‘t’ that is stored in the SplitChar value.  ‘b’ is less then ‘t’ so we take the LoNode to the next node.  This node contains a SplitChar value of ‘b’ so we have found our match!  Here is the code for the search:

        public object Search(string s)
        {
            TSNode p = root;
            int x = 0;
            while (p != null)
            {
                if (s[x] < p.SplitChar)
                {
                    p = p.LowNode;
                }
                else if (s[x] == p.SplitChar)
                {
                    x++;
                    if (x == s.Length && p.Value != null)
                    {
                        return p.Value;
                    }
                    p = p.EqNode;
                }
                else
                {
                    p = p.HiNode;
                }
            }
            return null;
        }

So those are the major methods of a Ternary Search Tree.  I will post the complete code up here shortly.  It’s also important to remember that even though a Ternary Search Tree is similar in use to other key-value type data structures it does have some major differences.  First, the key MUST be a string. Second, the Ternary Search Tree has the ability to return partial matches and even similar matches. Very Cool!

– Seth Long

February 1, 2008 Posted by | Data Structures | 4 Comments