QWAN logo

Connascence: Position (part 4)

Tags: architecture, coupling, design

In the previous posts, we introduced the Connascence model as a model of coupling and elaborated connascence by name, type and meaning. In this post, we will discuss Connascence by Position.

Connascence is a model for reasoning about coupling and defines three dimensions of coupling: strength, degree and distance, as the picture below shows.

connascence in three dimensions, from green to red

Connascence by Position

Connascence by Position means that two elements need to agree on the order of values.

connascence by position

Positional parameters are an example of Connascence by Position. In the code below, the line calling the Person constructor needs to keep the correct order as defined by the constructor signature. The compiler will not complain in case of a mistake.

1
2
3
4
5
class Person {
  constructor (String name, String surname, String town) { ... }
}

new Person("Jan", "Janssen", "Utrecht")

The degree of connascence can make positional coupling quite challenging: we can manage two parameters, but the longer the list of parameters is, the more risky it gets. An example is the C/C++ sprintf function, which has a variable parameter list that should match the format string provided. In the code fragment below, we need to make sure we pass the four parameters in the correct order.

1
2
3
4
5
6
    int id = 143;
    double price = 6.50;
    char grade = 'A';
    const char *tag = "hardware";

    sprintf(buffer, "id: %d, name: %s, price: %.2f, tag: %c", id, name, price, tag);

Refactoring Connascence by Position

Some languages allow us to refactor positional coupling to Connascence by Name, by using named parameters:

1
2
3
4
5
class Person {
  constructor ({ name, surname, town }) { ... }
}

new Person({ name: 'Jan', surname: 'Janssen', town: 'Utrecht' })

It is useful to check if a subset (or all) of the parameters form a Data Clump Then we can extract a new type or class to encapsulate those, as the code fragment below shows.

A Data Clump is a set of variables that belong together and travel together throughout the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
// from:
class Person {
  void Person(String name, String surname, String street, 
              String postalCode, String town) { ... }
}

// to:
record Name(String first, String last) {}
record Address(String street, String postalCode, String town) {}

class Person {
    void Person(Name name, Address address) { ... }
}

This reduces the Connascence by Position to Connascence by Type and encapsulates the details in the Name and Address types. We probably want to refactor this further, as we still have come positional coupling in Name and Address.

What’s next

This post is part of a series on connascence and coupling. In the next post, we will focus on Connascence by Algorithm, where two elements need to agree on the order of values.

RSS feed icon RSS feed