Temporal Coupling
Coupling is when there are two things, one of these things depend on the other thing. For example Class1 depends on Class2. This is bad because if Class2 changes then Class1 will become incorrect and may result in an error. This is why you should try not to couple things or your code will be non-flexible and will break if refactored.
Temporal coupling is similar, but it occurs between sequential method calls when they must stay in a particular order (they depend on things that could change / might not be there yet). Doing this is again non-flexible as trying to refactor this code at a later date will be sticky and probably end up in issues.
Here is an example of temporal coupling before and after:
Person person = new Person();
person.Initialise('Will');
String name = person.GetName();
This is bad as the name variable is reliant on person being initialised, this is temporal coupling. A way to loosen this coupling is by injecting the name into the constructor and check if it is valid like so:
Person person = new Person('Will');
String name = person.name();And the constructor would look like:
private final String name;
public Person(String name) throws Exception {
if (name == null) {
throw new Exception("invalid name");
}
this.name = name;
}
public String name() {
return this.name;
}This makes the code immutable, less complex and there is no temporal coupling.