Faur
Faur

Reputation: 5968

Purpose of simple wrapper function in C

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?

Upvotes: 4

Views: 19622

Answers (3)

Sorcrer
Sorcrer

Reputation: 1644

Basically a wrapper means , hiding all the related information of underlying routines by using our/a_developer's custom function.

You've mentioned that file name itself is db.c , so maybe the developer wants all the critical & important function which are used/declared must have starting of DB_

Upvotes: 0

Aki Suihkonen
Aki Suihkonen

Reputation: 20027

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;.

Upvotes: 7

Bathsheba
Bathsheba

Reputation: 234715

Wrappers, (or stubs), are often used to guard the other areas of your code from changes in the functions being wrapped.

It's also a useful way of interacting with dynamic libraries and shared objects.

Upvotes: 1

Related Questions