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): allocate(ressource) command(ressource) release(ressource)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