paint-brush
API Design — Temporal Couplingby@ZakTaccardi
3,862 reads
3,862 reads

API Design — Temporal Coupling

by Zak TaccardiApril 4th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Temporal coupling is a serious code smell. It should be <em>hard</em> for a developer to call a good API incorrectly.

Company Mentioned

Mention Thumbnail
featured image - API Design — Temporal Coupling
Zak Taccardi HackerNoon profile picture

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.

Usage of a BadApi that is temporally coupled

The above code compiled, yet an error was thrown are runtime. Why?

BadApi implementation

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

Usage of a good api

Other than passing invalid data, it is difficult to call this API incorrectly.

GoodApi implementation

Bonus points

Validate early, with type-safe objects instead of Strings.

Two possibile .login() implementations:

  1. fun login(username: String, password: String)
  2. 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!

Part 2: API Design — Handling Exceptions