Object-Oriented Design – Why Sequential Cohesion in Methods is Not Ideal

code-completedesignmethodsobject-orientedobject-oriented-design

I read from the seminal Code Complete book that method statements that require to be executed in order passing parameter from one to the next is a code smell and is an example of a sequential cohesion. Why is this not a good idea?

A contrived example of a sequential cohesion:

public Part createPart(input) {
        PartOne partOne = computePartOne(input);
        PartTwo partTwo = computePartTwo(partOne);
        PartThree partThree = computePartThree(partTwo);
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(partOne).add(partTwo).add(partThree).build();
    }

Here is the exert:

Several other kinds of cohesion are normally considered to be less than ideal:

Sequential cohesion exists when a routine contains operations that
must be performed in a specific order, that share data from step to
step, and that don't make up a complete function when done together.

An example of sequential cohesion is a routine that, given a birth
date, calculates an employee's age and time to retirement. If the
routine calculates the age and then uses that result to calculate the
employee's time to retirement, it has sequential cohesion. If the
routine calculates the age and then calculates the time to retirement
in a completely separate computation that happens to use the same
birth-date data, it has only communicational cohesion.

How would you make the routine functionally cohesive? You'd create
separate routines to compute an employee's age given a birth date and
compute time to retirement given a birth date. The time-to-retirement
routine could call the age routine. They'd both have functional
cohesion. Other routines could call either routine or both routines.

Best Answer

I think the example is actually Functionally Cohesive not Sequentially Cohesive. The inputs and outputs just happened to be related, but the methods could have been used independently. "Other routines could call either routine or both routines." - other routines could call any of the computePart methods.

Here is an example that I think better demonstrates the sequential cohesion.

public Part createPart(input) {
        setInput(input);
        computePartOne();
        computePartTwo();
        computePartThree();
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(this.PartOne).add(this.PartTwo).add(this.PartThree).build();
    }

Where as the above example has coupling between the stages here as the parts are inside the object and you can't really use them independently. They are tightly coupled - they actually "share data from step to step".

Related Topic