Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of simple wrapper function in C

Tags:

c

wrapper

In ex26 of 'Learn C the Hard Way' in the db.c file Zed defines two functions:

static FILE *DB_open(const char *path, const char *mode) {
return fopen(path, mode);
}
static void DB_close(FILE *db) {
fclose(db);
}

I have a hard time understanding the purpose/need for wrapping these very simple calls to fopen and fclose. What are, if any, the advantages of wrapping very simple functions, like the example given above?

like image 994
Toke Faurby Avatar asked Oct 28 '25 08:10

Toke Faurby


1 Answers

In this particular case a wrapper is used to hide the detail that DB_open, DB_read or DB_close all map to file operations.

This approach implements an abstraction layer through which all database related functions are to be accessed. Also this provides modularity, which may later allow adding more methods to open/read/close databases.

As explained by Michael Kohne in the comments, this wrapper should be improved to totally hide e.g. the type of FILE *db, by substituting it with struct DB_context *context;.

like image 177
Aki Suihkonen Avatar answered Oct 30 '25 22:10

Aki Suihkonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!