I'm reading data from a serial port and in case of an event I'd like to write the data to a file.
For this I have a small little function that opens the file to append one line of JSON data to it.
And then it closes the file when it leaves the scope of the function.
Since there may be "a lot" of data, it feels like opening and closing the file all the time comes with unnecessary overhead.
In order to replace the "write_to_file" function with a "write_to_some_database" in the future, I would like to keep the handling modular. How would you do that?
Open the file once as part of your application setup (likely right at the beginning of main), and pass it to the function every time you need to write to it.
You could declare a struct EventReport (or some better name for your context). The struct has the file as a member, so wherever you want to start reporting you creteate one by calling a named constructor EventReport::open(), and then you make the small funktion that appends a json line a method of that struct.
Anything that wants to append an event will need to borrow the struct, but that would still be true for the database handle or connection pool if you used a database instead. And it's modular, the borrowed EventReport and the append call would be the same if you changed the implementation of EventReport.