Video in progress
What is "temporal coupling"? How do you fix a class that requires its methods to be called in a certain order?
If a class only works correctly when its methods are called in a strict order (init() → configure() → run()) and nothing enforces it, that is temporal coupling. Breaking the order only fails at runtime, often with an NPE. The fix is to enforce the order through types and the constructor.
📖 Answer
var sender = new SmsSender();
sender.setGateway(gw);
sender.send("+998...", "kod: 1234"); // init() was forgotten → NPE on the token
sender.init();
The class expects the user to remember "first setGateway, then init, then send". That knowledge isn't written down anywhere.
Fixes:
- Put the required things in the constructor:
public SmsSender(SmsGateway gw) {
this.gw = gw;
this.token = gw.authenticate(); // a fully ready object
}
- Make the stages separate types, so the next step can only be obtained from the result of the previous one:
Connection conn = Connector.connect(url); // no Session without a connection
Session session = conn.login(user, pass); // no query without a login
session.query("...");
Now the wrong order can't even be written: the compiler stops it.
- If you can't split the stages, at least check the state and give a clear error:
if (token == null) throw new IllegalStateException("init() chaqirilmagan").
Spring has the same situation: relying on another bean not being ready yet inside @PostConstruct. If dependencies arrive through the constructor, this problem mostly goes away.
Sign up to mark studied questions and save your progress.