Feeds

Rethink code cohesion

Emergent Design: time to relate

High performance access to file storage

Book extract, part two Scott Bain's book Emergent Design: The Evolutionary Nature of Professional Software Development published by Addison Wesley looks at how to deliver and maintain robust, reliable, and cost-effective systems. In this, the second of five Reg Dev extracts, Scott tackles the complex subject of cohesion as a step to building simple and maintainable code.

Cohesion is an often misunderstood term. I think it may be due to the fact that it sounds a lot like adhesion, and so people think it means "how well things are stuck together." I have heard people describing a team of developers as a "good, cohesive team," meaning that they get along well together and work closely without conflict.

As nice as this may be for the team, it has nothing to do with cohesion. Cohesion refers to how much (or how little) the internal parts of something are working on the same issue, and how well they relate to each other. It is the quality of single mindedness or singleness of purpose, and it makes entities (classes, methods) easier to name and understand.

For example, a team is strongly cohesive if it has established an identity and all of its members are working toward the same goal, in a consistent manner, regardless of their personal feelings for each other. One clear sign of cohesion is how easy it is to put a name to something. If you can call a team "the GUI team," then likely everyone in it is working on the graphical user interface, which may indicate or help to bring about strong cohesion. If you have to refer to them as "the team that does the GUI, the database proxies, and some of the business logic," then the team is going to have a tougher time being cohesive (1), even if the members of the team are best buddies.

Cohesion in our code is much like this. One can consider cohesion at the method level, the class level, or even at higher levels like package, application, system, solution. For my purposes, method- and class-cohesion is all I will need.

Method cohesion

Consider the following code:


public class Application {
  public void process(String[] words) {
    // Loop through the array of Strings
    for(int i=0; i<words.length; i++) {
      String argument = "";
      // Reverse the characters in each String
      for(int j=words[i].length(); j>0; j--){
        argument += words[i].substring(j-1,j);
      }
      System.out.println(argument);
    }
    // Test for two particular Strings
    if(words.length == 2){        
      if(words[0].toLowerCase().equals("mighty") && 
words[1].toLowerCase().equals("mouse"))
         System.out.println("...here he comes to save the day.");
    }
  }
        
  public static void main(String[] args){
    Application myApp = new Application();
    myApp.process(args);
  }
}



This is a simple little application that takes any parameters passed on the command line, reverses the characters, tests for the name of a remarkable fellow, and then makes an appropriate comment.

But it has weak cohesion.

Why?

A clue lies in the generic quality of the method name process(). It does not tell us what the method does because to name the method properly it would have to be something like:

reverseCharactersAndTestForMightyMouse()

Difficult-to-name methods are a good sign that you have weak method cohesion. In essence, the method process() is doing too much, and it is doing things that are not related to each other. Reversing the order of characters in each string parameter and testing them all together for a particular name are activities that have nothing to do with one another.

We could fix this by putting these different steps into their own methods, then calling those methods from process(), such as in the following code:


public class Application {

  public void process(String[] words) {
    for(int i=0; i<words.length; i++) {
      reverseCharacters(words[i]);
      System.out.println(words[i]);
    }
    if(isMightyMouse(words)) {
      System.out.println("...here he comes to save the day.");
    }
  }

  private String reverseCharacters(String forward){
    String reverse = "";
      for(int j=forward.length(); j>0; j--){
        reverse += forward.substring(j-1,j);
      }
      return reverse;
  }

  private boolean isMightyMouse(String[] names){
    boolean rval = false;
    if(names.length == 2){        
      if(names[0].toLowerCase().equals("mighty") && 
         names[1].toLowerCase().equals("mouse"))
         rval = true;
    }
    return rval;
  }
        
  public static void main(String[] args){
    Application myApp = new Application();
    myApp.process(args);
  }
}

When I read the process() method, I am reading a series of steps, each step accomplished by another method. Process() has become an organizing method, a scaffold that creates the general shape of the behavior, but then delegates the actual steps to other methods.

1. A team of human beings, of course, can be quite effective but lack cohesion. A cross-functional team, for example, can be a good thing. I just want to make it clear what this word means, and to suggest that software entities (which are not intelligent) should be cohesive.

High performance access to file storage

More from The Register

next story
Android engineer: We DIDN'T copy Apple OR follow Samsung's orders
Veep testifies for Samsung during Apple patent trial
Windows 8.1, which you probably haven't upgraded to yet, ALREADY OBSOLETE
Pre-Update versions of new Windows version will no longer support patches
OpenSSL Heartbleed: Bloody nose for open-source bleeding hearts
Bloke behind the cockup says not enough people are helping crucial crypto project
Microsoft lobs pre-release Windows Phone 8.1 at devs who dare
App makers can load it before anyone else, but if they do they're stuck with it
Half of Twitter's 'active users' are SILENT STALKERS
Nearly 50% have NEVER tweeted a word
Windows XP still has 27 per cent market share on its deathbed
Windows 7 making some gains on XP Death Day
Internet-of-stuff startup dumps NoSQL for ... SQL?
NoSQL taste great at first but lacks proper nutrients, says startup cloud whiz
This time it's 'Personal': new Office 365 sub covers just two devices
Redmond also brings Office into Google's back yard
US taxman blows Win XP deadline, must now spend millions on custom support
Gov't IT likened to 'a Model T with a lot of things on top of it'
prev story

Whitepapers

Securing web applications made simple and scalable
In this whitepaper learn how automated security testing can provide a simple and scalable way to protect your web applications.
Five 3D headsets to be won!
We were so impressed by the Durovis Dive headset we’ve asked the company to give some away to Reg readers.
HP ArcSight ESM solution helps Finansbank
Based on their experience using HP ArcSight Enterprise Security Manager for IT security operations, Finansbank moved to HP ArcSight ESM for fraud management.
The benefits of software based PBX
Why you should break free from your proprietary PBX and how to leverage your existing server hardware.
Mobile application security study
Download this report to see the alarming realities regarding the sheer number of applications vulnerable to attack, as well as the most common and easily addressable vulnerability errors.