Part I. Cohesion
When we talk about a method being highly cohesive we mean that it performs one (and only one) piece of logic. Another way to look at it is each unit of code (class, method, etc) should have a single purpose that is easy to understand from a glance. This is a long-standing principle of software engineering (the Single Responsibility Principle). Methods with low cohesion perform multiple procedures and it can be said that they have have multiple purposes.
When we talk about a class being highly cohesive, we mean the class encapsulates one (and only one) piece of business logic as well. For instance, a highly cohesive middle tier would have classes that clearly seperate abstract data transport classes, their instantiation, database functionality and business logic. If we have one monolithic class that does everything our code most likely be considered to have very low cohesion.
We can also talk about the cohesiveness of packages (or assemblies in the CLR world). Each assembly should encapuslate one (and only one) business domain. If we have an assembly that does exposes logging, sending order confirmation emails, performs accounting calculations and washes our dirty dishes it is not very cohesive and is probably going to be a pain to maintain.
Let's look at an example of a huge method with very low cohesion that performs a series of logical sub-steps in an overall process of retrieving data from the database and building data transport objects. My personal rule of thumb is that if a method does not fit on the screen and I have to scroll to see the whole thing, it is probably too long and needs to be refactored.
Here are the steps:
- Instantiating a database connection
- Instantiating a database command
- Opening the connection
- Executing the command
- Reading the results
- Getting the ordinals from the data reader
- Getting the record values and Instantiating new instance of object
As you glance through the code below, notice how difficult it is to completely absorb how this method works at first glance. If you give up, just scroll to the end of this code block where we'll start the refactoring.
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
// instantiate the connection
using(SqlConnection connection = newSqlConnection(ConfigurationManager.ConnectionStrings[CONNECTION_STRING_KEY].ConnectionString))
using(SqlCommand command = new SqlCommand("spGetEmployee", connection)) // instantiate the command
{
command.CommandType = CommandType.StoredProcedure;
// try to open the connection
try
{
connection.Open();
}
catch (InvalidOperationException ex)
{
// log exception
throw;
}
catch (SqlException ex)
{
// log exception
throw;
}
catch (Exception ex)
{
// log exception
throw;
}
// execute the reader & read the results
using(SqlDataReader reader = command.ExecuteReader())
{
Int32 m_NameOrdinal, m_DeptOrdinal;
// get the ordinals
try
{
m_NameOrdinal = reader.GetOrdinal(NAME);
m_DeptOrdinal = reader.GetOrdinal(DEPARTMENT);
}
catch(System.IndexOutOfRangeException ex)
{
// log exception
throw;
}
Collection<Employee> result = new Collection<Employee>();
// read the results
while(reader.Read())
{
try
{
Employee emp =new Employee();
emp.Name = reader.IsDBNull(m_NameOrdinal) ?String.Empty : reader.GetString(m_NameOrdinal);
emp.Department = reader.IsDBNull(m_NameOrdinal) ?String.Empty : reader.GetString(m_DeptOrdinal);
result.Add(emp);
}
catch (IndexOutOfRangeException ex)
{
// Log the exception
throw;// rethrow or handle gracefully here
}
catch (Exception ex)
{
// Log the general exception
throw;// rethrow or handle gracefully here
}
}
return result;
}
}
}
Whew! That was painful. All we really want to do is understand what the code does quickly and be able to dig in further if we want. If we wanted to test any one step of our process it would be difficult because everything is thrown in the same pot.
Example of High Cohesion
Below, we have a method with the same functionality, but constructed in a highly cohesive manner with no implementation logic in it at all... the one (and only one) purpose of this method is orchestrating a bunch of reusable method calls. As a result we will have less repeated code in the project because there is a lot of logic in each sub-step that is reusable. It has the same functionality as our non-cohesive method... Do you think it is easier to quickly understand?
public IEnumerable<Employee> GetEmployeesFromDb_HighCohesion()
{
using (SqlConnection connection = BuildConnection())
using (SqlCommand command = BuildCommand("spGetEmployee",CommandType.StoredProcedure, connection))
using (SqlDataReader reader = ExecuteReader(command, connection))
{
return new MapperFactory()
.BuildEmployeeMapper()
.ReadAll(reader);
}
}
Part II. The Journey: Refactoring Code From Low to High Cohesion.
The first step in refactoring code with low cohesion is to identify what and where the logic steps are. The first thing we'll start looking at is object instantiation. We can refactor all code responsible for instantiating objects into builder methods which often makes a tremendous difference.
The first instantiation we come to is the SqlConnection object. Let's build a factory for our SqlConnection objects. This will have immediate reusable payoffs because we'll be building a new connection every time we need to hit the database.
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
// instantiate the connection
using(SqlConnection connection = newSqlConnection(ConfigurationManager.ConnectionStrings[CONNECTION_STRING_KEY].ConnectionString))
using(SqlCommand command = new SqlCommand("spGetEmployee", connection)) // instantiate the command
{
... code continues here...
We select the instantiation code and use Visual Studio's (2008) Refactoring tool to extract the method. After our refactoring, we have a very cohesive method that can be reused every time we need a database connection and so we'll have less repeated code in our project. As you can see, with a little formatting, this method is very cohesive and easy to understand at a glance, so if our fellow developers are drilling down from our main method to this one (or we are revieweing code we wrote ourselves a while ago), there should be no confusion as to what the method is actually doing.


As an aside: If you don't have Studio08, check out http://www.jetbrains.com/resharper/ for a really nice plug-in with some great refactorings for Studio05. Their current version for Studio08 does not support LINQ syntax and so is a little messy if you are using the new language features in 3.5, but there is a new release coming in March of this year that I'm looking forward to that is supposed to support LINQ syntax in Studio08.
To get back on subject...This is now what our builder method looks like (with a few line breaks added for extra measure)...
private SqlConnection BuildConnection()
{
return newSqlConnection(
ConfigurationManager
.ConnectionStrings[CONNECTION_STRING_KEY]
.ConnectionString);
}
And our main method is now a bit simpler.
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
using(SqlConnection connection = BuildConnection())
using(SqlCommand command = new SqlCommand("spGetEmployee", connection)) // instantiate the command
{
//... code continues here...
The next place we are instantiating an object and can refactor to a builder method is when we build the SqlCommand.
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
using (SqlConnection connection = BuildConnection())
using(SqlCommand command = new SqlCommand("spGetEmployee", connection))
{
command.CommandType = CommandType.StoredProcedure;
//-- code continues here --

Following the same process as last time, we'll select the construction section of the code and extract it to a method and we end up with the following:
private static SqlCommand BuildCommand(SqlConnection connection)
{
return newSqlCommand("spGetEmployee", connection);
}
Which is better, but still can be improved. What we want is a reusable method with one step in our process fully encapsulated. If you think about it, the stored procedure name really should be passed in so we have a more generic "BuildCommand()" method, so we'll make the sproc name a parameter
private static SqlCommand BuildCommand(String cmdText, SqlConnection connection)
{
return newSqlCommand(cmdText, connection);
}
And we'll modify our source method so it now looks like...
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
using (SqlConnection connection = BuildConnection())
using (SqlCommand command = BuildCommand("spGetEmployee", connection))
{
command.CommandType = CommandType.StoredProcedure;
//--code continues here--
Better... but still there is room for improvement. The CommandType can really be thought of as a part of building a command and should probably be moved into the builder method and exposed as a parameter.
private static SqlCommand BuildCommand(String cmdText, CommandType cmdType,SqlConnection connection)
{
SqlCommand cmd =new SqlCommand(cmdText, connection);
cmd.CommandType = cmdType;
return cmd;
}
And our calling code is getting much easier to read because BuildCommand() does everything required to build the SqlCommand object.
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
using (SqlConnection connection = BuildConnection())
using (SqlCommand command = BuildCommand("spGetEmployee",CommandType.StoredProcedure, connection))
{
// try to open the connection
try
{
//--code continues here---
While we're at it.... If we know that we may need parameters at some point in our project, we can preemptively make one further alteration to our method so we can pass them in when they are needed.
private static SqlCommand BuildCommand(String pCommandText, CommandType pCommandType,SqlConnection pSqlConnection,params SqlParameter[] pSqlParameters)
{
SqlCommand cmd =new SqlCommand(pCommandText, pSqlConnection);
cmd.CommandType = pCommandType;
if (null != pSqlParameters && pSqlParameters.Length > 0)
cmd.Parameters.AddRange(pSqlParameters);
return cmd;
}
So now we have a very reusable and easy to understand builder method for any SqlCommand object with parameters.
The next object we are instantiating is the SqlReader. Right now, instantiating our reader consists of opening the connection to the db and executing the command. So what we're going to do is extract a method that builds the reader and move the step to safely open the connection to our new method.
public IEnumerable<Employee> GetEmployeesFromDb_LowCohesion()
{
using (SqlConnection connection = BuildConnection())
using (SqlCommand command = BuildCommand("spGetEmployee",CommandType.StoredProcedure, connection))
{
// try to open the connection
try
{
connection.Open();
}
catch (InvalidOperationException ex)
{
// log exception
throw;
}
catch (SqlException ex)
{
// log exception
throw;
}
catch (Exception ex)
{
// log exception
throw;
}
// execute the reader & read the results
using(SqlDataReader reader = command.ExecuteReader())
{
Int32 m_NameOrdinal, m_DeptOrdinal;
// get the ordinals
try
{
m_NameOrdinal = reader.GetOrdinal(NAME);
//-- code continues --



ras aliPosted Nov 21, 2010, 12:49 AM
respected Sir, i m beginner and read ur article this difficult for me to understand the code given in ur example. sir, plz send me code in c++ of high cohesion example if u have time and happy to answer me. my email is boston [email protected] Thanks
Mike GoldPosted Feb 19, 2008, 12:54 PM
I've been looking at spaghetti code for the last year, and some times I think the sole purpose of my job is to refactor incohesive code into cohesive code. (I'm sure I'm not alone here). Thank you so much for addressing this in this article.