ConstructiCat Logo
CodeBust.
Browse section ▾

Sequential Coupling.

Sequential coupling is an antipattern in which a class only works when callers invoke its methods in one specific, unstated order.

In object-oriented programming, sequential coupling (also known as temporal coupling) is a form of coupling where a class requires its methods to be called in a particular sequence. This may be an anti-pattern, depending on context.

Methods whose name starts with Init, Begin, Start, etc. may indicate the existence of sequential coupling.

Using a car as an analogy, if the user steps on the gas without first starting the engine, the car does not crash, fail, or throw an exception - it simply fails to accelerate.

Sequential coupling can be refactored with the template method pattern to overcome the problems posed by the usage of this anti-pattern.

Example

This Parser works only if its methods are called in exactly the right order. Nothing in its interface says so: forget tokenize() and buildTree() fails at run time with a NullPointerException.

class Client {
    Node run(String text) {
        Parser parser = new Parser();
        parser.setInput(text); // must be called first
        parser.tokenize();     // must be called second
        return parser.buildTree();
    }
}

class Parser {
    private String input;
    private List<String> tokens;

    void setInput(String text) { this.input = text; }
    void tokenize() { tokens = List.of(input.trim().split("\\s+")); }
    Node buildTree() { return new Node(List.copyOf(tokens)); } // NullPointerException if tokenize() was skipped
}

A single public method now runs the steps itself and hands each one the result of the previous step, so the wrong order can no longer be expressed:

class Client {
    Node run(String text) {
        return new Parser().parse(text);
    }
}

final class Parser {
    Node parse(String text) {
        List<String> tokens = tokenize(text);
        return buildTree(tokens);
    }

    private List<String> tokenize(String text) { return List.of(text.trim().split("\\s+")); }
    private Node buildTree(List<String> tokens) { return new Node(List.copyOf(tokens)); }
}

When subclasses must customize individual steps, the Template Method pattern keeps the same guarantee: the base class fixes the order and subclasses only override the steps.

Adapted from the Wikipedia article “Sequential coupling” (revision 1320717439), available under the CC BY-SA 4.0 license; the text has been edited and examples added.