C++ - Where to store a global counter? - c++

The diagram http://www.freeimagehosting.net/uploads/2fd3f4161c.png
Here's the Minimalist-UML diagram of an app I've been working on. It's supposed to simulate the management of a bunch of sensors relating to different measurements.
Please ignore the House class, the diagram is outdated...
However, I have trouble. Each sensor (sound, contact, heat, pressure, gas - All of these inherit from sensor) has an unique ID, starting at 0 for the first one and ending at the total number of sensors - 1.
For good practices' sake, where shall I store the total number of sensors, so the classes I'm using for input/output of files (saving and loading) and insertion of new sensors can access and increment that counter?
Thank you for your time!

One option would be to create a static function in your Sensor class that increments and returns a static counter variable. The constructor for Sensor could call this function to get an ID.
// header file
class Sensor
{
...
protected:
static int getId() { return id++; }
private:
static int id;
int myId;
};
// .cpp file
int Sensor::id = 0;
Sensor::Sensor(...)
: myId(getId())
...
{}
I'm ignoring threading and persistence issues here. But hopefully this gives you a better idea.

Whatever object creates the sensors should assign the identifiers to the sensors.
If multiple objects create sensors, then they should be assigned a pointer or reference to a provider of identifiers when they are created and they should query that provider for a new unique identifier as they create new sensor objects.

Your unique ID, like a database table ID will likely have some issues.
You will probably find, eventually, that your ID needs to persist across sessions--that your window's ID is used in some other relationship.
You may, some day, also find that it needs to be unique across multiple server/client sets.
I'm just suggesting that you should consider these issues off the bat.
As for where the ID should be generated, since all your "Sensor" classes inherit from one base class, I think I'd generate it via a threadsafe method in that base class--and I'd store it there as well.

what's the problem? do you use a Vector to store your sensors? define a Vector of holding sensor-objects in the house.
can access and increment that counter
you don't have to do this, the Vector does it for you

Have a look at the Singleton pattern assuming you don't want to do it with a database of some sort.

Related

OOP for global system/task monitoring class

I'm trying to create a performance monitor of sorts to run on a Particle board (STM32 based). I'm used to programming in c so the OOP approach is a bit new but I think it would fit well here.
For the purpose of this question let's assume I have two types of monitors:
Frequency. The application can call a "tick" method of the monitor to calculate the time since it last ran and store it.
Period- call a "start" and "stop" method of the monitor to calculate how long a process takes to run and store it.
What I would like to do is to create instances of these monitors throughout my application and be able to report on the stats of all monitors of all types from the main module.
I've read about the singleton design pattern which seems like it might be what I need but I'm not sure and I'm also concerned about thread safety with that.
I'm thinking I will create a "StatMonitor" class and a derived class "FrequencyMonitor" and "PeriodMonitor". Monitor would be a singleton and everywhere I wanted to create a new monitor I would request an instance of "Monitor" and use that like so:
freqMonitor * task1FreqMonitor = StatMonitor::GetInstance()->Add_Freq_Monitor("Task1");
The StatMonitor would track all monitors I've added and when I wanted to print the stats I could just call the printAll method which would iterate it's array of monitors and request their results like so:
StatMonitor::GetInstance()->PrintAllStats();
Am I going down the right path?
Your path sounds good, except that FrequencyMonitor and PeriodMonitor should not derive from the class that "manages" all these monitors (let's call it MonitorPrinter).
MonitorPrinter should be a singleton and could look like this:
class MonitorPrinter
{
public:
static MonitorPrinter& getInstance()
{
static MonitorPrinter monitorPrinter;
return monitorPrinter;
}
void printAllStats()
{
for (const auto& [_, frequencyMonitor] : _frequencyMonitors)
frequencyMonitor.print();
for (const auto& [_, periodMonitor] : _periodMonitors)
periodMonitor.print();
}
FrequencyMonitor& getFrequencyMonitor(std::string name)
{ return _frequencyMonitors[name]; }
PeriodMonitor& getPeriodMonitor(std::string name)
{ return _periodMonitors[name]; }
private:
MonitorPrinter() = default;
std::map<std::string, FrequencyMonitor> _frequencyMonitors;
std::map<std::string, PeriodMonitor> _periodMonitors;
};
Demo
(The const auto& [_, frequencyMonitor] is a structured binding).
FrequencyMonitor and PeriodMonitor should not have anything to do with singletons, and from your description, they need not be part of a class hierarchy either (as they have different interfaces). If you want, you can prevent users (other than the MonitorPrinter) from instantiating these classes using other techniques, but I won't elaborate on that here.
In short, there is no need to use OOP here. Use a singleton to provide (and keep track of) the monitors, and implement the monitors to your liking. Be wary of thread safety if this is relevant (the above is not thread-safe!).

Regarding RSU address in message

I added the following lines in onData method of my TracIDemoRSU11p.cc file:
void TraCIDemoRSU11p::onData(WaveShortMessage* wsm) {
findHost()->getDisplayString().updateWith("r=16,green");
annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobi->getCurrentPosition(), "blue"));
static int count=0;
count++;
if(count>100)
{
wsm->setCount(count);
sendMessage(wsm->getWsmData());
}
}
What I want is to get the vehicle's address which has sent the data as well.
Also, is there any problem in using the static variables in the method?
I have defined a count variable in wsm message and I want to send the count value along with the vehicleId in the message.
Amending the message definition to include a vehicle id is allowed. So is using static variables in C++. I don't think it is a good idea though.
The static variable will be shared among all instances of that class (that is, across nodes and - possibly - simulation runs). I would recommend using a regular member variable of some class.

Usage of Global variables in C++

I am working on an application that reads files from an input directory,processes them and
loads them on to DB. The two classes Filelist and CurrentFile are part of the application.
The class defintions are as below.
class Filelist
{
//list of files
list of files;
// pointer to the current file
CurrentFile *ptr
};
class CurrentFile
{
vector<list of records>
methods to process the records
..
..
};
I have to add another Audit structure that keeps track of successfully processed records and
errored out records. This audit structure gets loaded into the DB after all the files are
processed.
struct Recaudit
{
//record to keep track of
//Various counts
int successcnt;
int errorcnt;
billedcnt;
some other counts related to the records
};
This audit record has its data set across multiple methods of CurrentFile.
Can this audit record be made a member variable of CurrentFile (or) should I declare it as a
static global variable?
I guess, that Audit is some kind of log? You have to make a decision about its purpose.
If it's a general purpose log with an option to store information about import statuses, it shall be made a singleton (a "safe" kind of global variable). It's consistent with OOP rules, yet the class is easily available for all interested parties.
If it's designed specifically for storing information about import statuses, it has to be available for object performing the calculations, but shall be stored one level above (eg. in object containing list of all calculation objects). In your case the FileList should be a parent for the Audit (eg. it should maintain its lifetime), but CurrentFile should get an instance of Audit in the constructor, such that it can store results of the calculation within. In both cases be cautious about the multitasking, if you plan to implement one.

Am I violating an OOP design guideline here? Couple of interesting design pickles

I'm designing a new power-up system for a game I'm creating. It's a side scroller, the power ups appear as circular objects and the player has to touch / move through them to pick up their power. The power up then becomes activated, and deactivates itself a few seconds later. Each power-up has its own duration defined. For simplicity's sake the power ups are spawned (placed on the screen) every X seconds.
I created a PowerUpManager, a singleton whose job is to decide when to create new power ups and then where to place them.
I then created the Powerup base class, and a class that inherits from that base class for every new Powerup. Every Power-up can be in one of three states: Disabled, placed on the screen, and picked up by the player. If the player did not pick up the power up but moved on, the power up will exit the screen and should go back from the placed state to the disabled state, so it can be placed again.
One of the requirements (that I) put in place is that there should be minimal code changes when I code up a new Power up class. The best I could do was one piece of code: The PowerUpManager's constructor, where you must add the new power-up to the to the container that holds all power-ups:
PowerupManager::PowerupManager()
{
available = {
new PowerupSpeed(),
new PowerupAltWeapon(),
...
};
}
The PowerUpManager, in more details (Question is coming up!):
Holds a vector of pointers to PowerUp (The base class) called available. This is the initial container that holds one copy of each power up in the game.
To handle the different states, it has a couple of lists: One that holds pointers to currently placed power ups, and another list that holds pointers to currently active power ups.
It also has a method that gets called every game tick that decides if and where to place a new power up and clean up power ups that weren't picked up. Finally it has a method that gets called when the player runs into a power up, that activates the power up (Moves it from the placed to the active list, and calls the power up's activate method).
Finally, once you understand the full picture, the question:
I needed a way for client code to ask if a particular power-up is currently active. For example: The player has a weapon, but there is a power up that replaces that weapon temporarily. Where I poll for input and recognize that the player wants to fire his weapon, I need to call the correct fire method - The alternative weapon power up fire method, and not the regular weapon fire method.
I thought of this particular demand for a while and came up with this:
template <typename T>
T* isActivated() // Returns a pointer to the derived Powerup if it exists in the activated list, or nullptr if it doesn't
{
for(Powerup *i : active) // Active is a list of currently active power ups
{
T *result = dynamic_cast<T*>(i);
if(result)
return result;
}
return nullptr;
}
So client code looks like this:
PowerUpAltWeapon *weapon = powerUpManager->isActivated<PowerUpAltWeapon>();
if(weapon)
...
I thought the solution is elegant and kind of neat, but essentially what it is is trying to convert a base type to a derived type. If that doesn't work, you try the next derived type... A long chain of if / else if, it's just disguised in a loop. Does this violate the guideline that I just described? Not casting a base type to all of its derived types in a long chain of if / else if until you get a hit? Is there another solution?
A secondary question is: Is there a way to get rid of the need to construct all the different power ups in the PowerupManager constructor? That is currently the only place you need to make a change if you want to introduce a new power up. If I can get rid of that, that'd be interesting...
This is based on your design, but if it was me I choose an ID for each PowerUp and a set of IDs in the client, and each time a user posses a PowerUp that ID will be added to its set and ... you know the rest. Using this technique I can do fast look up for every PowerUp and avoid dynamic_cast:
std::set<PowerUp::ID> my_powerUps;
template< class T > bool isActivated() {
return my_powerUps.find( T::id() ) != my_powerUps.end();
}
And about your second question, I have a similar program that load some plugins instead of PowerUp, I have a pure virtual base class that contain all methods that required by that plugin and implement it in shared modules and then at startup I load them from an specific folder. For example each shared module contain a create_object that return a plugin* (in your case PowerUp* of course) and then I iterate the folder, load modules and call create_object to create my plugins from them and register them in my plugin_manager

C++ DBI Class - best/developer friendliest style

In our current project, we need some high level DBI for different databases. It should provide the following features:
in memory cache - the DBI should be able to cache all reads, and update the cache on writing calls (the application we are coding on is heavy threaded, and needs fast access to the current data all the time). The memory cache will be based on boost::multi_index
automatic sql building - We don't want to parse a sql statement to lookup in the memory cache
As we need to provide functions for: defining a table layout, do selects, do inserts, do updates, joins, ..., the interface will get very complex.
We need a good way to invoke the interface function.
There are many styles around, but we could not find any useful for our usage.
Here a few examples:
SOCI
sql << "select name, salary from persons where id = " << id, into(name), into(salary);
We don't want some SQL statements, so we would have to define what and from a different way.
pqxx
Conn.prepare("select_salary",
"select name, salary from persons where id = $1")
((string)"integer",prepare::treat_direct);
The heavy usage of the overloaded operator() is just ugly, but it could work for us too.
Any suggestions how to design the interface?
How about using object relational mapping? Here's some code fragment ideas off the top of my head - I've only done this in Python, never in C++, and only for fairly simple databases. There's a list of frameworks on Wikipedia that should avoid too much wheel-related R&D.
class people: public dbi_table
{
// id column handled by dbi_table.
name: string_column;
salary: money_column;
};
class cost_center: public dbi_table
{
name: string_column;
office: foreign_key<offices>;
};
class people_cost_center_link: public link_table
{
// Many-many relationships.
};
Then you can manipulate records as objects, all the relational stuff is handled by the framework. Querying is done by defining a query object and then getting an iterator to the results (see the ODB wikipedia page for a code example).
I would do it like this (and it'd be good in c++ point of view, dunno if it's correct database stuff):
struct Handle { int id; }
class DBI
{
public:
virtual Handle select(int column_id)=0;
virtual Handle select(int column1, int column2)=0;
virtual Handle id(int id)=0;
virtual Handle join(Handle i1, Handle i2)=0;
virtual void execute_query(Handle i)=0;
};
Usually these functions would be implemented like this:
Handle select(int column_id) {
return new_handle(new SelectNode(column_id));
}
where new_handle function would just insert SelectNode to std::vector or std::map and create an handle for it.