There are two ways to do the same thing (pseudo code)
-
Define databaseHandle in the parent function, and use it as a global in this scope:
function API() { function openDatabase() { return databaseHandle; } databaseHandle = openDatabase() function getItem(i) { databaseHandle.get(i) } function addItem(name) { databaseHandle.add(name) } }
-
Define a function for getting this handle, and then get it when we need it:
function API() { function openDatabase() { return databaseHandle; } function getItem(i) { databaseHandle = openDatabase() databaseHandle.get(i) } function addItem(name) { databaseHandle = openDatabase() databaseHandle.add(name) } }
The first option seems simpler, and I see it in many examples. But the second one seems to me more reliable and obvious in what it does (and a bit redundant).
What is the best practice here? If there’s another, better way, I’d like to hear about it. Thanks.
I’d go with the second approach, with a change which releases the handle when done. If each method takes care of getting, operating and releasing its own handle, then your application should be better suited to scale up (assuming you have some sort of pooling underneath).
With the first approach, it is hard to say what will happen should two different threads call each method separately at the same time.
10