Stretch out for your cohesion

Today I have something of a warm-up. A few simple exercises that can help you define the type of cohesion that a class has. In Structured Design (for more details about the article itself go to the A brief history of coupling and cohesion post) the authors proposed a simple technique, which was to describe a module’s (class in our case) function in a single sentence. 

So now let’s look into their guidelines:

1. “If the module is functional in nature, it should be possible to describe its operation fully in an imperative sentence of simple structure, usually with a single transitive verb and a specific non-plural object.”

For example:

  • Calculate VAT
  • Calculate commission
  • Read the temperature
  • Retrieve the order info

2. “If the only reasonable way of describing the module’s operation is a compound sentence, or a sentence containing a comma, or a sentence containing more than one verb, then the module is probably less than functional. It may be sequential, communicational, or logical in terms of cohesion.” 

For example:

  • Update time spent on the task, employee’s work time, and invoice based on time card. – probably communicational cohesion, as all elements are communicationally connected by a time card. 
  • Update the order and save it. – sequential cohesion.

3. “If the descriptive sentence contains such time-oriented words as “first,” “next,” “after,” “then,” “start,” “step,” “when,” “until,” or “for all,” then the module probably has temporal or procedural cohesion; sometimes but less often, such words are indicative of sequential cohesion”

For example:

  • Before sorting, save data, remove duplicates, and check checksums – temporal cohesion as we assume that order is not essential here.
  • Download exchange rates, next send sales results to the sales department and new orders to the orders department. – probably procedural cohesion as we model the following steps where order is essential but output data of elements is not input data of those following them, so it’s not sequential.

4. “If the predicate of the descriptive sentence does not contain a single specific objective following the verb, the module is probably logically cohesive. Thus, a functional module might be described by “Process a GLOP.” A logically bound module might be described by “Process all GLOPS,” or “Do things with GLOPS.””

5. “Words such as “initialize,” “clean-up,” and “housekeeping” in the descriptive sentence imply temporal cohesion.”

Those guidelines might be considered too general, but in my opinion it is an excellent exercise sometimes to ask ourselves “what does that class actually do?”. 

What about a situation when we are considering adding a new element into an existing class? In Structured Design (the book), the authors give us a similar technique based on the principle of association. This time we should answer the question “why does the element fit there?”. As a result, we could end up with the following statements:

1. “Z is associated with this module containing X and Y, because X, Y and Z are all related by virtue of having the ‘glop’ property”

2. “It’s OK to put Z into the same module as X and Y, cause they’ are all related in such-and-such a manner”

3. “It’s OK to put Z into the same module as X and Y, cause they’re all members of the glop set.”

Last but not least, a hint from me: model problems/features in a group. Why? Since the bigger our understanding of the problem, the higher the cohesion is. However, there is a tiny catch here. Each of us analyzing a problem has their own version of it in mind and the same goes for solutions to it. That’s why it is so important to share this process with others. Through sharing, we build a common understanding of the problem within the team.

P.S. If you have enjoyed this article and would like to always have it with you offline or you would like to have some super sketch notes with types of coupling and cohesion to print out and stick them above your bed, don’t hesitate and download an ebook, that I have for you. You will find there a few great posts about rotting design, coupling and cohesion put together into PDF, EPUB and MOBI formats.

* indicates required
Photo by kike vega on Unsplash

The forgotten realm of Cohesion

For the history of cohesion go to A brief history of coupling and cohesion. Below, we will focus on the concept itself and its types.

Now it’s time to focus on the classes themselves and the elements they consist of. When do we know that a specific element fits into a certain class? Sometimes what we assume does, actually doesn’t necessarily do it to for our colleague. In such a case, cohesion comes to the rescue. In general, it’s a measure of how elements go together.

Regarding cohesion, there was a problem with what to call it to start with. At the beginning it was named “intramodular functional relatedness”, but this term was found to be a bit clumsy. Cohesion was also called “binding” or “functionality”. In his book Myers calls it “module strength”, which is also entirely accurate as it can tell us how tightly elements of a class are bonded in the context of the functionality they perform – to what extent they are related. Finally, the term “cohesion” was chosen by analogy to the cohesion of groups – a similar concept in sociology. 

Glenn Vanderburg wrote a post where he explained why in his opinion programmers have a problem with understanding the whole concept of cohesion. He argues that the name is not as  self-explanatory as is the case of coupling and it is not used so often in everyday life, either. Because of that, we can’t refer it to our daily situations. To better visualize the term, he proposes comparing it to other words with the same root. For example, “adhesion”, which describes stickiness. If something sticks to something else, it is a one-sided process, often aided by a third-party – glue in most cases. He also used an example of duct tape that doesn’t have to fit into anything as due to its stickiness it sticks to almost anything. On the other hand, cohesive elements match each other perfectly, and there is no need to use any glue between them.

The better our understanding of a designed problem is, the higher cohesion we can end up with. This is why it is absolutely vital to spend time on getting familiar with the problem itself and the business domain. Once we know it quite well, we should focus on grouping elements in a way that reflects the problem. Thanks to that, we maximize relationships between them.

Now let’s think what drives the grouping of elements into a specific class. To answer that, we should take a closer look at types of cohesion, starting with one with the lowest and ending up with the highest degree of it.  

Types of Cohesion

Coincidental Cohesion

The first criterion for assigning elements to a specific class could be an actual lack of any criteria. It means that elements are grouped totally randomly – a real free-for-all. Such classes are created coincidentally and not in the process of design.

If we were to give this type any number on the scale of cohesion, we would probably give it a zero as there is no cohesion here at all.

Classes with this type of cohesion are quite rare but if we find any, they are probably artifacts of bad modularization. Usually, they are created because we find some sequence of methods’ calls in a few different places in our application, and we decide to extract them to a single class. Extracting, as we know, is not a bad thing, but if single methods do totally different things and, worse still, if we do it without thinking about what those sequences do in each of the contexts, we probably should leave them as they are. Otherwise, we can end up with a class that we will have to modify when something changes in one of those contexts but not in others.

Coincidental cohesion – total randomness in grouping elements into a class.

Logical Cohesion

In logical cohesion, elements of a class are grouped because they solve problems from the same category. Logically there is something that they have in common even though they have different functionalities.

A good example here could be mathematical operations, as each of them can do various things, but often they are grouped in some Math or Utils class with… mathematical operations.

The above-mentioned Utils classes are usually good examples of this kind of cohesion. One to rule them all!

Logical cohesion – class’ elements solve the same type of problems. For example,  a class that aggregates all mathematical operations.

Temporal Cohesion

If logical cohesion is combined with another grouping criterion that is the moment of execution, we will probably get temporal cohesion.

The best examples of this type of cohesion would be classes/modules that initialize, stop, or clean something. Initialization methods are logically connected as they “initialize something”. What is more, those methods usually have to be executed at some specific point in time or period.

Quite often, such classes/modules need to have this type of cohesion, and any attempts to change it to more cohesive types are highly ineffective.

Temporal cohesion – elements of the class have to be executed within the same period.

Procedural Cohesion

The next type is procedural cohesion, and it usually occurs when instead of modelling a domain we focus on an algorithm of execution – the order of steps that have to be executed to get from state “A” to state “B”. It may lead us to the approach where we end up modelling the algorithm itself and not the problem that we were supposed to solve.

Cohesion in this type is higher as elements are not only grouped because of their moment of execution like in temporal cohesion, but they also have to be executed in a specific order.

Loops, multiple conditions, and steps in the code can show evidence of procedural cohesion. Those are usually classes that, while being analysed, make us want to take a piece of paper, a pencil and start to draw a block diagram. 

Procedural cohesion – usually when we model algorithm itself and not the problem that we were supposed to solve

Communicational Cohesion

The first type of cohesion that focuses on the modelled problem is communicational cohesion. The criterion for grouping elements into a class here is that they are communicationally connected, which means that they work on the same input or return the same type of output data. Thanks to that, it can be easier to reuse the whole class in different contexts.

Classes like this have origins in thinking about operations that can be done on some particular set of data, or on the other hand – operations that have to be executed to get that set of data.

Communicational cohesion – elements in the class are grouped because they are communicationally connected, so they use the same input data or return the same output data.

Sequential Cohesion

At the stage when we group elements because of their sequence of data processing, so that the output of one element is at the same time input of the next one we probably have a brush with sequential cohesion.

There could be only one small issue here. If we have such a sequence, we can cut it in different ways. It means that created classes can do more than one functionality, or quite the opposite – only some part of the functionality. That’s the only reason why in the hierarchy of cohesion types it stands below the last one, which is functional cohesion.

Sequential cohesion – we group elements because of the sequence of data processed by them.

Functional Cohesion

We achieve it when all elements within a class are there because they work together in the best possible way to accomplish the goal – functionality. Each processing element of such a class is its integral part and is critical for the functionality of the class. The class itself performs no less and no more than one functionality.

What’s interesting, mathematical operations are often mentioned as an example of functional cohesion because they do exactly what they should and nothing more than that. I have also mentioned mathematical operations in logical cohesion, but there all operations were grouped in a Utils or Math class, and now I mean more creating a class per operation. So the responsibility of a single class would be only to perform a single operation.

It can be quite easy to judge whether a class has functional cohesion when we deal with a “small” functionality, but at higher levels of abstractions it can become a bit tricky. That’s why we can try to do it by looking for signs of other types of cohesion – similar to the case of data coupling. A bit like a shell game. For that, chapter “Exercises” could be helpful. You will find there quite interesting high-level exercises that can help you with everyday work to define what type of cohesion your class has, so don’t stop, keep reading :).

Functional cohesion – elements within a class are there because they work together in the best possible way to accomplish the goal – functionality.

Nonlinearity

When it comes to types of cohesion, one more thing is worth mentioning. In the book Reliable Software Through Composite Design as well as in Structured Design, the authors suggested assigning a weight to each of those types. Nevertheless, what is most important here they were quite reticent about it. That’s because they insisted that it might be a bit too early for it and they didn’t want it to influence future research into cohesion. They emphasized that values were chosen “based on educated guesses” and “these aspects of the model must be verified and refined based on data collected”.

The only reason why they decided to assign those weights, was to show that in their opinion those weights have nonlinear values and for example, in Structured Design, they were proposed as follows:

0: coincidental

1: logical

3: temporal

5: procedural

7: communicational

9: sequential

10: functional

When we can identify what types of cohesion our classes have, and we can see some places for improvements, these weights can be helpful as they can show us where we should utilize our energy. If we, for example, see that some class has sequential cohesion, it means that it is already almost “ideal” and maybe it makes no sense trying to get to functional cohesion. Instead, it is better to take care of places where the gain is higher, for example, between temporal and procedural cohesion.

Finally, some food for thought

Imagine a situation when without going into any details your colleague tells you “that new class that you’ve just created has poor cohesion.” I can imagine how adrenaline hits you, and at this stage, you probably can react in very different ways. You can flee, fight, or… debate.

Assuming that he or she is not a wild animal, and we are not going to end up as his or her dinner, I encourage you to take the third option. Maybe such a situation is just an opportunity to discuss and define what we understand as cohesion. Maybe we have a different understanding from our colleague. Next, we can also discuss what types of the term we can identify in our system and whether we allow them there or not. It’s not like some of them are right or wrong by default and we should avoid thinking in this way.

If you feel like some “stretching exercises” concerning cohesion, go to Stretch out for your cohesion.

P.S. If you have enjoyed this article and would like to always have it with you offline or you would like to have some super sketch notes with types of coupling and cohesion to print out and stick them above your bed, don’t hesitate and download an ebook, that I have for you. You will find there a few great posts about rotting design, coupling and cohesion put together into PDF, EPUB and MOBI formats.

* indicates required

A brief history of coupling and cohesion

From the very first time when coupling and cohesion were defined, there was one issue with both of them. Let me ask you a few questions:

– how can I recognize that one class is tightly coupled with another?

– how can I verify whether or not a specific class is cohesive?

Well, my class is definitely highly cohesive and loosely coupled with others, but a class of my colleague’s… hmmm… he or she had better reconsider their future career as a developer.

It turns out that each of us can have different images of what is loosely/tightly coupled and what is or is not cohesive. What is most interesting, any of us can be right. Why is that so? Both concepts are highly abstract. How do we deal as human beings with such concepts? We look for analogies to our daily lives. You can quickly validate this by looking into the most highly rated answers to general questions about coupling and cohesion on Stack Overflow. You will find a ton of analogies. Just take a look:

“Car and Spare parts analogy of coupling”

“You and the guy at the convenience store.” – loose coupling

– “The cheese store.” – high cohesion

– “You and your wife.” – tight coupling

Analogies are great, and we like them. They help us to get the context and shed some more light on the problem. But do they really explain everything? I don’t think so. Ok, so now it’s time to dig into Wikipedia or any other pedia. What we see there are some classical definitions that I more or less included earlier in this article. Then we scroll a bit down, and we notice something more as there are types of coupling and types of cohesion. No one told us about them, so let’s take a look at what more your search engine of choice returned. So now is the moment when real fun begins. There are a lot of publications and books. One author says that, for example, there are only two types of coupling, another says there are twelve. Someone else that all the others are wrong because they didn’t consider this and that. At the same time, some of the publications even use different names; for example, cohesion is sometimes referred to as “functional binding” or “strength”. 

When did it all begin?

To answer this question, we need to go back in time to 1974, when Larry Constantine, Glenford Myers, and Wayne Stevens published in IBM Systems Journal their article called Structured Design. They described coupling and cohesion there, but actually, Larry Constantine is considered to be the father of these concepts.

One year later, the book Reliable Software Through Composite Design by Glenford Myers was published. Quite a big part of it was dedicated to both concepts. On a side note, I can say that it’s a great book; it’s written in an accessible way, and the most fascinating thing about it is that while reading it you can have an impression that in the last 50 years little has actually changed when it comes to the challenges in software design and its modularity.

Then after another few years, Larry Constantine and Edward Yourdon published their book called Structured Design – the same as the article from 1974. They were also referencing Mayers’ book, which goes to show that those guys for few years were doing a lot of research in the area of coupling and cohesion.

We could probably say now that those were the 70s, so it should be quite outdated now. Procedural programming was standard back then, they had modules, and now we do OOP, we have our cool, shiny classes. Why should we even care?  Well, it turns out that even though paradigms have changed, coupling as well as cohesion are still with us and they feel pretty fine in OOP. When in the early 90s Timothy Budd published his book An Introduction to Object-Oriented Programming you could find there that counterparts of modules in OOP are classes. Personally, I would go further and say that both concepts are so universal, that I can easily imagine, for example, a loose/tight coupling between packages in Java or even between microservices.

I hope that I have sparked off your curiosity and you would like to know more about both concepts as well as their above-mentioned types :). Don’t wait and go here to read more about coupling or here about cohesion.

P.S. If you have enjoyed this article and would like to always have it with you offline or you would like to have some super sketch notes with types of coupling and cohesion to print out and stick them above your bed, don’t hesitate and download an ebook, that I have for you. You will find there a few great posts about rotting design, coupling and cohesion put together into PDF, EPUB and MOBI formats.

* indicates required

Rotting design BINGO!

Some time ago within the confines of getting back to basics, I read “Design Principles and Design Patterns.” by Uncle Bob. It is a publication that is almost 20 years old, and mostly you can find there a few design patterns called SOLDI at that time. Today those patterns are probably known to all of us as SOLID principles, but that’s a different story. What got my attention there was an idea of rotting design.

When we start a project, we usually spend a significant amount of time designing it within the team. Usually, we end up with a clear vision of how it should work. We fix the boundaries – allowing or disallowing some behaviors in our brand new system. As a result, we get a design that is state-of-the-art – at least to our current knowledge. All team members ritually put their signatures in blood on it and agree to respect it till the end of its days.

In the beginning, everything looks great. We develop with ease, first versions get to production, time goes by, and we are receiving first feature requests. Next to them appear little exceptions to our original agreements. Some tiny “hacks” here and there. Just because they are “temporary solutions” or because we “need to fix a bug quickly.” Thus our design starts to rot, and it is not the bleeding edge anymore.  At some point, it has nothing in common with our first approach, and someone says “we need to rewrite it.” However, it can happen that not everyone would be so enthusiastic about doing so. Especially people that are not close to the code but have to approve such a decision and justify its business viability. The worst case scenario is that we stay with rotting design without the chance to redesign it. If so, any changes, even the smallest ones, are hard to implement. The situation becomes very frustrating for developers as well as product owners, managers and so on, up to the top of the food chain hierarchy.

That’s usually the moment when there starts a witch-hunt and the temptation to blame the whole evil thing on constant changes or blurry requirements, customer’s lack of business knowledge, lack of documentation or user stories, you name it. There are situations when it’s true, but still, we are required to write code that is resilient and easily maintainable. Why? Because in most cases we work in agile environments, and by default, requirements will change. Our goal is to be one step ahead of customers. This is the world we live in.

Let’s chill out a bit for a moment and play BINGO:

Rotting design BINGO

So? BINGO? If you have won, I have some good and bad news. The bad news is that probably you are struggling with the rotting of the design in your application. The good news is that I’m going to shed some more light on its disease. However, before that, I would like to ask you to take a closer look at the examples on the bingo board. Each of them shows evidence of one out of four symptoms of rotting design.

Symptoms of rotting design

Symptom no. 1 – rigidity

We can notice it when a seemingly simple change in the code triggers a chain reaction of unexpected changes in the entire application. As a result, it becomes tough to introduce any changes as it is very time-consuming.

Real life example could be a situation when a product owner comes to a team and asks about the estimation of adding just this one, tiny checkbox to the form. After a while, the team estimates that two devs are going to do it in a two week period. Unbelievable? Oh, I assure you it’s true ;). 

As a result, non-critical issues are not being fixed, because Product Owner or manager are afraid of spending the team’s time on fixing them, as they don’t know how long it could take.

Symptom no. 2 – fragility

When after a change in one place, you get bugs in totally different parts of the system that are logically not connected with the original place, you are probably dealing with fragility.

You fixed the tax policy, but you also introduced three new bugs related to adding products to the cart, customers filtering in admin panel and error logging.

Once again fear appears because no one knows where and how many business functionalities break after bugfix. There is also a suspicion that developers have lost control over the code.

Symptom no. 3 – immobility

Now I want you to imagine a situation when you implement a new feature, and you recall a piece of code that does exactly what you need. You find it, analyze it and leave it there, rewriting it in your functionality. But why? Why can’t you reuse it? Because the overhead of extracting it and satisfying all its dependencies is so huge that it simply doesn’t make any sense.

Symptom no. 4 – viscosity

When we develop our application, we can do it in one of two ways: according to the current design or against it. In the case when it is easier to follow the latter approach, it probably means that viscosity is in attendance. We can easily link it to all those situations when we knew how something should be coded, but instead we did some little hack to deliver our feature quickly. To sum up, it is easier to do those tiny hacks than follow the design rules.

Four main symptoms of rotting design.

What the hell is going on here?

Now it’s time to finally get to know what disease our design is suffering from. Once we have found out that it is not because of changing requirements, what else can it be? Well, the most common reason for that is the wrong dependency management in our code. If so, two old concepts come to the rescue: coupling and cohesion.

Coupling can be described as a strength of the relationship between classes or modules. Typically we talk about its two types: tight and loose coupling. However, as we all know, between two extreme values, there is always this gray area where we can place a lot of different cases, which is the case here, too. More about it later on.

Cohesion, on the other hand, is a degree of how elements of a specific class/module go together, how they match the class and each other. They all should effectively work towards a common goal. They should all naturally mesh with each other, without any “glue” used to connect them. When it comes to cohesion, we also usually describe it as low or high, but guess what: there is more than that.

Generally, we consider good design as one that it is easily maintainable, resilient to changing requirements and having loosely coupled, independent classes, that do exactly what they were created for. In other words, such a design is marked by loose coupling and high cohesion.

Strong coupling and low cohesion (on the left) vs. loose coupling and high cohesion (on the right).

Now you can do two things. Either you can gain some more knowledge about the origins of coupling and cohesion and why developers usually have issues with understanding those concepts. For that, I encourage you to read A brief history of coupling and cohesion. Alternatively, you can go to the posts dedicated to coupling or cohesion. Have a good reading!

P.S. If you have enjoyed this article and would like to always have it with you offline or you would like to have some super sketch notes with types of coupling and cohesion to print out and stick them above your bed, don’t hesitate and download an ebook, that I have for you. You will find there a few great posts about rotting design, coupling and cohesion put together into PDF, EPUB and MOBI formats.

* indicates required