Wrapping (procedural) APIs

Why wrap a (procedural) API of a third-party library / host application – instead of using the API straight away? Here are some reasons plus some simple techniques to accomplish just that:
* Wrapping the API makes unit testing much easier because you can mock your own classes instead of mocking the API itself (which tends to have more dependencies)
* Creating your wrapper may actually deepen your understanding of the API
* You may be able to tie up a few loose ends in the API (e.g. mix of deprecated and new API functions to accomplish a task)
* Creating your wrapper may simplify the API (witness the change from AddPopupItem() to AppendPopupItem() in the sample provided below
Here are some simple techniques for wrapping:
* Save on parameters – Instead of using AddPopupItem(..., long dialogID, short popupID, short insertAfterEntry, String entry) you could use MyAppendPopupItem(long dialogID, short popupID, String entry) – not a substantial improvement, but if combined with the next techniques quite powerful…
* Transmogrify the API into an object-oriented API – Use myDialog.AppendPopupItem(short popupID, String entry) instead
* Make it even more object-oriented – Use myPopup.Append(String entry) instead
There are a number of arguments against wrapping an API – but at the end of the day, I’m quite firmly in the “Wrap it” camp.

Comments are closed.