Reputation: 66
I am currently using C++ on a microcontroller and I am having an issue where I don't know what the proper implementation is:
I am for example using an serial interface class which takes care of configuring the serial port (setting baud, data bits...). Since I only want to do it at the initialization phase of my MCU at the start, I don't know how to handles this with classes.
Shall I make a global class/singleton which I create at the initialization phase (in this way I can keep my serial parameters) or shall i create a class everytime I need to use the serial interface (but this would reopen my serial line - or do I leave the constructor empty)?
Thanks a lot in advance.
Upvotes: 0
Views: 148
Reputation: 27115
I try to avoid global variables and singletons.
I defined a class with a constructor that accepts a pathname and configuration to open the port, and a destructor that closes the port. Then, I declared a static
local instance of it in main(...)
and I passed references to it in to the constructors of other classes that needed to use the port.
Passing the reference around (as opposed to declaring a global instance, or a global function to get a singleton) is what enabled me to write unit tests for the other classes in which the tests passed in a references to mock serial port objects.
Upvotes: 2
Reputation: 1290
You are asking for opinions because all options are valid.
I do believe creating a singleton to store the configuration and resources needed is a good approach. This way you can implement RAII idiom, and gain easy access when needed.
Upvotes: 1