jeudi 17 février 2022

Cpp: using scoped resource without passing arguments around

I've been struggling with a design problem in cpp for a while. I have a resource (In this scenario a configuration). This configuration is global, and it is initialized and cleared multiple times during the program execution (If it's cleared, there is no current configuration, and if something needs it will fail).

I want to use this configuration inside a class- but I do not want to pass it around as a parameter, since it will change dozens of functions, and complicate classes interfaces a lot (and sometimes it even might be a weird dependency, especially if some derived classes need it and some do not).

Now I use a weird singleton, that can be cleared and initialized, but the codebase grew, and it looks bad now

Pseudo code for demonstration:

Configuration::init(buffer);
SomeClass some_class(param1, param2);
some_class.do_dirty_work_using_the_configuration();
Configuration::clear()

This code is not RAII and I actually use a class to initialize and clear the configuration in the real implementation.

I heard the solution should be dependency injection, but as far as I know there is no good implementation for it in cpp

Thank you!

Aucun commentaire:

Enregistrer un commentaire