Click here to Skip to main content
15,861,168 members
Articles / Programming Languages / Visual Basic

Cohesion of Methods

Rate me:
Please Sign up or sign in to vote.
1.62/5 (8 votes)
14 Jul 2005CPOL4 min read 39.2K   12   1
This articles focuses on building your classes and the cohesion factors you need to keep in mind while writing programs.

Introduction

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."

Example

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.

Functional Cohesion

A method does one thing; one thing only. No complications added to it.

VB
Public Sub New()
    Mybase.New()
    InitializeObject()
End Sub

The above sample method performs the initialization process. Nothing else. This level of cohesion is highly desirable and acceptable when writing classes.

Sequential Cohesion

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.")
    sw.Close()
End Sub

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.

Communication Cohesion

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:

VB
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 

    ' Create first column
    myColumn = New DataColumn()
    myColumn.DataType = System.Type.GetType("System.Int32")
    myColumn.ColumnName = "id"
    Table1.Columns.Add(myColumn)
    Table2.Columns.Add(myColumn)
    ' Create second column.
    myColumn = New DataColumn()
    myColumn.DataType = Type.GetType("System.String")
    myColumn.ColumnName = "item"
    Table1.Columns.Add(myColumn)
    Table2.Columns.Add(myColumn)
    ' Create new DataRow objects and add to DataTable. 
    Dim i As Integer
    For i = 0 to 9 
        myRow = myDataTable.NewRow()
        myRow("id") = i
        myRow("item") = "item " & i
        Table1.Rows.Add(myRow)
        myRow("item") = "Grade " & i
        Table2.Rows.Add(myRow)
    Next
    ' Create a DataView using the DataTable.
    myDataView = New DataView(Table1)
    ' Set a DataGrid control's DataSource to the DataView.
    DataGrid1.DataSource = myDataView
    MyDataView = New DataView(Table2)
    DataGrid2.DataSource = myDataView
End Sub

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.

Temporal Cohesion

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.

VB
Sub GetRequiredData(Option as Boolean) 
    Dim ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; " & _ 
                  "Data Source=c:\purchase.mdb"
    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)
    Conn.Open()
    If Option = True then
        Dim myReader1 As OleDbDataReader = Comm.ExecuteReader()
        Call DisplayData(myReader1)
    Else
        Dim myReader2 As OleDbDataReader = Comm.ExecuteReader()
        Call DisplayData(myReader2)
    End if
    Conn.Close()
End Sub

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.

Conclusion

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder BB Systems CIT-GPNP
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionYou missed some, no? Pin
theahmed14-Jul-05 14:17
theahmed14-Jul-05 14:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.