The word "Cohesion" means the act, process, or condition of cohering – joining together. It has been in wide use in the fields of physics, biology, and mathematics, and to your surprise, writing too. Cohesion acts as glue that holds a piece of writing together. Writing of code, whether it is structured or object-oriented, needs a little thinking of cohesion. Transition of control flow, repetition of keywords, and referencing the variables are some of the program elements that need attention while programming for cohesion. Yeah, next time when you write code, consider cohesion!
Cohesion of Classes
Class cohesion is considered as one of most important characteristics in object-oriented design and software metrics.
Classes are the basic units of object-oriented programs, and serve as the units of encapsulation promoting their modifiability and reusability. The quality of classes is determined by the cohesion measure that refers to the degree of relatedness of the members in a class. High cohesion is a desirable property of classes.
Member methods serve a common purpose, and allow you to organize a class logically. But, poorly written methods degrade the implementation or management routine of a class – what is called as "Object Policy."
If you have ten methods that act as utilities for network operations, you can very well split the class into two classes: one serving the utilities and the other, network operations.
There are several metrics that measure class cohesion in object-oriented systems - in terms of connections among member methods within a class, and some other based on instance variables usage criteria.
Now, let us look into the cohesion of methods and how they are implemented in .NET.
Cohesion of Methods
Method cohesion focuses on the methods you write inside the class. A method should clearly state the intention of why it is written. Otherwise, it is weakly cohesive. More tasks you accumulate within a method, more likely, you do wrong programming.
Several levels of cohesion have been identified and accepted by software quality persons. Here is the list that ranges from the most acceptable to the least acceptable form method cohesion.
A method does one thing; one thing only. No complications added to it.
Public Sub New()
The above sample method performs the initialization process. Nothing else. This level of cohesion is highly desirable and acceptable when writing classes.
A single method performs a series of steps in a sequence, which together logically makes up the entire process.
Public Shared Sub Main()
' Create an instance of StreamWriter to write text to a file.
Dim sw As StreamWriter = New StreamWriter("TestFile.txt")
' Add some text to the file.
sw.Write("This is the ")
sw.WriteLine("text for the file.")
The above method performs a sequence of tasks such as opening a file, write to a file, and close a file. Suppose you want to insert an additional step (reading the file, sorting the data, processing the data) that would weaken the cohesion. Alternatively, you can transfer control to another method to perform these tasks and return back to the closing of the file.
This level of cohesion allows you to write several tasks in a single method. You include tasks that are invariably unrelated.
Take a look at this method:
Private Sub CreateDataTableAndDisplay()
Dim Table1 As DataTable = New DataTable()
Dim Table2 As DataTable = New DataTable()
Dim myColumn As DataColumn
Dim myRow As DataRow
Dim myDataView As DataView
myColumn = New DataColumn()
myColumn.DataType = System.Type.GetType("System.Int32")
myColumn.ColumnName = "id"
myColumn = New DataColumn()
myColumn.DataType = Type.GetType("System.String")
myColumn.ColumnName = "item"
Dim i As Integer
For i = 0 to 9
myRow = myDataTable.NewRow()
myRow("id") = i
myRow("item") = "item " & i
myRow("item") = "Grade " & i
myDataView = New DataView(Table1)
DataGrid1.DataSource = myDataView
MyDataView = New DataView(Table2)
DataGrid2.DataSource = myDataView
In the above method, you can see that two data grids need to be populated by data from two tables created during runtime. Even though it is acceptable to perform the second table's task, when you start adding a few more things, the level of cohesion would collapse and your method will look ugly.
It allows a single method to perform a whole bunch of activities that need to be performed at the same time. This is the least-acceptable level of cohesion, which programmers have to avoid.
Sub GetRequiredData(Option as Boolean)
Dim ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
Dim Conn As New OleDbConnection(ConnStr)
Dim Comm1 As New OleDbCommand("Select prod_id, prod_name from product, Conn)
Dim Comm2 As New OleDbCommand("Select item_id, item_name from item, Conn)
If Option = True then
Dim myReader1 As OleDbDataReader = Comm.ExecuteReader()
Dim myReader2 As OleDbDataReader = Comm.ExecuteReader()
In the above method, you will notice that the author has used an
If condition to determine which method to call. Instead, he could have used two separate methods altogether.
There are other levels of method cohesion like logical cohesion and co-incidental cohesion, which do a dirty job and should not be followed by programmers.
Methods in a class need to be loosely coupled so that they don't depend on the operations of other methods. When methods access or share a global variable, they become undesirably coupled to each other. Instead, those should be passed as parameters to a method. Similarly, if a method is included in the class just to write into global variables, for the benefit of other methods, cohesion levels come down substantially.