Global counter in an application: bad practice?

In my C ++ application, I sometimes create different output files for troubleshooting purposes. Each file is created at a different stage in our pipeline operation, and it is difficult for him to know which file appeared before which another (the timestamps of the files show the same date).

I am going to add a global counter to my application and a function (multithreading) that increments and returns this global counter. I can then use this counter as part of the filenames I am creating.

Is this considered bad practice? Many different modules need to create files, and they are not necessarily related to each other.

+2


a source to share


5 answers


I think adding the current system time to the filename with a high enough precision would be cleaner and easier to implement and maintain



//helper function to encapsulate details
string makeFileName(string filename)
{ return filename + getCurrentTime(); }

void MyClass::SomeMethod()
{
   File f = CreateFile(makeFileName("myclassfile"));
   ...
}

      

+2


a source


If it's just for debugging, is temporary and won't be released, you can do whatever is quicker and easier.



If, on the other hand, this is something that can stay in your application for a long time and possibly break into a release, then I will definitely take more time and write a basic file creation module available to all your other modules.

+4


a source


This is not bad practice at all.

In C ++, I would write a singleton class that would contain a counter and multi-threaded security. This would be cleaner and avoid using global variables as in c (you would use static class variables instead).

+2


a source


I personally created a factory for these files that would be responsible for returning the file. You can have a static variable for the counter for this function (or class).

+1


a source


I have generally abandoned global variables of any type in favor of static member variables. They serve the same function, and you can limit how static members can be changed and accessed.

0


a source







All Articles