Montag, 4. April 2016

Avoiding Temporal Coupling - Part 1/2

Every now and then we try to watch Uncle Bobs cleancoders videos. In episode 4, "Function Structure" the issue of temporal coupling is discussed. Temporal coupling is something we encounter quite often: to work with a database you first need to connect to the database. Next you do your work with the database and as the last step you disconnect. The same applies to working with a file: first you open it, then you perform your actions on the file handle/ object and when your done you close it.

The order of this actions is important - you can't call the database disconnect method before you call the connect method. Also, those temporal couplings are often hidden in the background. Quite often some global init method created this database connection your are using for you, at least this is what you believe. When shutting down the application you are hoping that there is another magic method which closes the connection.

In order to deal better with temporal coupling Uncle Bob suggests a technique called "passing a block". The idea is to allocate and to release resources at the point where you need it. The following pseudo code illustrates this approach:
withRessource(ressource, command):
Python supports this pattern out of the box with its context manager . Also Java 7 and following has a similar construct.

When looking at the pattern I immediately thought that implementing "passing a block" in plain C isn't too hard.  Function pointers are your friend here. Wait for the second part of this post to see the implementation of withFile, a function which first opens a file, executes your desired actions and then closes this file.

Keine Kommentare:

Kommentar veröffentlichen