Feeds

Rethink code cohesion

Emergent Design: time to relate

3 Big data security analytics techniques

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.

SANS - Survey on application security programs

More from The Register

next story
OpenBSD founder wants to bin buggy OpenSSL library, launches fork
One Heartbleed vuln was too many for Theo de Raadt
Got Windows 8.1 Update yet? Get ready for YET ANOTHER ONE – rumor
Leaker claims big release due this fall as Microsoft herds us into the CLOUD
This time it's 'Personal': new Office 365 sub covers just two devices
Redmond also brings Office into Google's back yard
Ubuntu 14.04 LTS: Great changes, but sssh don't mention the...
Why HELLO Amazon! You weren't here last time
Patch iOS, OS X now: PDFs, JPEGs, URLs, web pages can pwn your kit
Plus: iThings and desktops at risk of NEW SSL attack flaw
Next Windows obsolescence panic is 450 days from … NOW!
The clock is ticking louder for Windows Server 2003 R2 users
Batten down the hatches, Ubuntu 14.04 LTS due in TWO DAYS
Admins dab straining server brows in advance of Trusty Tahr's long-term support landing
Red Hat to ship RHEL 7 release candidate with a taste of container tech
Grab 'near-final' version of next Enterprise Linux next week
Apple inaugurates free OS X beta program for world+dog
Prerelease software now open to anyone, not just developers – as long as you keep quiet
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.
3 Big data security analytics techniques
Applying these Big Data security analytics techniques can help you make your business safer by detecting attacks early, before significant damage is done.
The benefits of software based PBX
Why you should break free from your proprietary PBX and how to leverage your existing server hardware.
Mainstay ROI - Does application security pay?
In this whitepaper learn how you and your enterprise might benefit from better software security.
Combat fraud and increase customer satisfaction
Based on their experience using HP ArcSight Enterprise Security Manager for IT security operations, Finansbank moved to HP ArcSight ESM for fraud management.