API Design — Temporal Coupling
Make development easier with obvious APIs enforced at compile time
Temporal coupling is a serious code smell. It should be hard for a developer to call a good API incorrectly.
The above code compiled, yet an error was thrown are runtime. Why?
The badApi.url
field was not set before calling login()
. Requiring certain methods of a class to be called in a specific order is known as temporal coupling, which slows down development velocity.
How to avoid temporal coupling
Other than passing invalid data, it is difficult to call this API incorrectly.
Bonus points
Validate early, with type-safe objects instead of Strings
.
Two possibile .login()
implementations:
fun login(username: String, password: String)
fun login(username: Username, password: Password)
#1 allows the developer to accidentally mix-up the username and password fields (code compiles because both parameters are Strings), while #2 makes that impossible.
Code is available on GitHub.
Catch the conversation on Reddit!
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!