So instead of asking Al about that, I try here to hope to get some different insights.
I wanna try and keep it short to the point.
My baseproject is pretty big and maybe complicated(Toolkit to make Projects), and works with DI(dependency injection). (5k lines+)
Not the topic here, but related.
I was making a simple Buzzer class.(So simple not worth talking about).
But I maybe intend to make some stuff public, drivers, diff stuff, and in the end the whole toolkit.
This Buzzer is regarded hardware, and is/should be independent of my project.
So the question, how to best integrate it(and make not too complicated for release), so it doesn't pollute global space, or do you guys global just everything?
Case A: (Buzzer/Class STATIC)
(QUESTION 1):
When the class(Buzzer) is static(=no internal state it needs to save)
It is pretty simple:
namespace or static use: ?? (QUESTION 1)
Buzzer::ON or Buzzer::Melody1.
Case B: (Buzzer/Class NOT STATIC)
(QUESTION 2):
I just realized the simplest way is to do it like other libs. Just import where needed, and make an instance.
But this end up with more instances. So let's pretend I would need more instance control.
The question
So Singleton or DI? (QUESTION 2)
More extended explanation:
I have two layers:
-myEsp32 (takes care of instances of all hardware INSIDE the esp32(i2c, pwm, BT,Wlan etc)
User just grabs it all with one command, and can be used class like:
-myEsp32.pwm.dutyCycle(50)
-myEsp32.ic2.write(message)
The second layer:
Is basically the User/Project layer.
The user just got the instance of myEsp32 and inserts all modules with myEsp32 if they need it.
example:
SensorManager sensorManager(_myEsp32);
sensorManager.init();
GrowController growController(_myEsp32);
growController.init();
DataManager dataManager(_myEsp32, sensorManager, growController);
dataManager.init();
I could use Dependency Injection as in my baseproject, but that would mean, less clear to others, if I would make it(or something similar) public?
So then I could also use Singletons, which would get rid of DI, and makes sure only one global instance exists. But less clear, who owns what, but simpler.
This could be applied to a buzzer for example.(It has a simple getInstance() function).
There could also be made a good case, to use that for myEsp32 as well, since it is a hardware instance, their should be only one!?
But I heard that singletons are considered bad practice, cause more difficult to unittest. (although I did make mock functions to test stuff)
So DI or Singletons where possible, or even mix?
Or are there better other options? ![]()