Functors for library configuration

Hello,

I have a library that I’m working on, living, that I would like to add some configuration to. Specifically, living has a failsafe mechanism similar to that used by Ctypes for (specifically dynamic and not static) function pointers, whereby it requires you to free items explicitly and prevents the garbage collector from collecting the value if you don’t, to assure soundness. Like Ctypes, when this occurs, I print to stderr letting you know it happened.

However, I’d like to allow the user to pass their own function that is used for logging, and indeed turn off this behaviour if they find it annoying or it is impacting performance too much.

To that end, I’ve functorized the main part of the library, where a user provides a module with the logging function and other configuration parameters, and the module returned acts accordingly.

See this line for the structure of a default config module, and
this function for how it’s used.

I’m wondering if there is alternatives to this approach for passing user-defined behaviour to a module, or if there are otherwise other techniques I should know about here. One (slight) annoyance is that the module that ends up using this module needs to now be a functor too. I suppose this probably cannot be avoided, but I thought I’d ask.

Some options:

  • let users pass a callback that will be called whenever this event happens (you don’t have to pass it a formatted string)
  • expose a global ref that will be used by your library
  • use a logging library in a way that’s not enabled by default / can be disabled on a component per component basis (I think logs supports this)
1 Like

Thanks, I didn’t think of using a logging library in that way. I think I’ll end up using the functor interface after all, though.