Decouple visualization methods and application [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
this is my first question on SO, so please bear with me.
We develop an application, which gathers data, and we have methods that let us visualize the data in various ways. With growing number of methods, we decided to separate the application and the visualization methods. I'm wondering what is the best way to accomplish this. I've come up with the following code, which somewhat tries to separate the two, but still ...
Is there a better way to do it?
// forward declaration
class App;
// Interface to all visualization methods
struct Methods {
virtual void show(App * a) = 0;
};
// Some visualization method
struct Method0 : public Methods {
void show(App * a) {
a->getData();
}
};
class App {
public:
vector<Methods *> methods;
void run() {
// draw all registered methods
for (auto m : methods)
m->show(this);
}
int getData() {
// parse and precompute data (time-consuming, thus do it only once)
// return the required data (not just an int..)
return 42;
}
};
void main() {
App a;
// register some methods
a.methods.push_back(new Method0());
// run the application
a.run();
// clean up
for (auto m : a.methods) delete(m);
}
EDIT
I think Alexander and Petr pointed me in the correct direction, thank you. I'll follow Petr's suggestion and try to separate the data into another class.
Addressing the comment by Spektre:
Developed on Windows (MSVC), otherwise platform independent.
The visualization is mostly static and changes based on user input. I guess 10 updates per second is an upper bound on the refresh rate.
What do you mean by data transfer times?
Memory is not an issue.
The data is a bunch of vectors of objects holding other vectors of objects, 5 dimensions in total.
One visualization is similar to ROC curve, containing several curves, so we need to traverse part/all the dimensions and compute some statistics. The result is shown in the following figure.

What you have there already looks quite good. As you have probably already assumed, you are not the first person to have this kind of problem. The standard solution for the separation of your data from your visualization is known as the Model View Controller Pattern (MVC), which not only decouples the presentation of your data from the data itself, but also allows for simple manipulation of the data from the display.
If you just want to display your data, then you might want to have a look at the Observer Pattern. Then again, what you have is already quite close to this pattern.

In addition to an answer by Alexander, I will mention that actually you did not completely separated data and visualization. The Application class still knows both about the internal structure of data and about the vector of visualization methods. What you should better do is to have a separate class, say Data, the will be doing all the computations you need, and then have the main class (App for example) that will just handle registration of methods and passing data to them.
Something like
class Data;
struct Methods {
virtual void show(Data * a) = 0;
};
struct Method0 : public Methods {
void show(Data * d) {
d->getData();
}
};
class Data {
public:
int getData() {
// parse and precompute data (time-consuming, thus do it only once)
// return the required data (not just an int..)
return 42;
}
}
class App {
public:
vector<Methods *> methods;
Data* data;
void run() {
// draw all registered methods
for (auto m : methods)
m->show(data);
}
};

Related

should a class manage its instantiated objects? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
lets assume I have a number instance of a class vehicle instantiated. if the vehicle object wants to query other existing vehicles for some reason ( for example finding the nearest vehicle), should the class manages the instantiated objects through static members and methods as in the code below? is this a good design pattern? is this a common standard? is there any pitfall if i take this approach?
#include <vector>
#include<algorithm>
struct Location {
double x, y, z;
Location(double xx, double yy, double zz) : x(xx), y(yy), z(zz) {}
};
class Vehicle {
private:
Location l;
public:
Vehicle (Location ll) : l(ll) {
vv.push_back(this);
}
static std::vector<Vehicle*> vv;
~Vehicle() {
std::vector<Vehicle*>::iterator it;
// removing the Vehicle object from the list of existing vehicles
for (it = vv.begin(); it != vv.end(); it++){
if (*it == this) {
vv.erase(std::remove(vv.begin(), vv.end(), this), vv.end());
}
}
}
Vehicle& find_nearest_vehicle () {
// code to iterate through list of existing vehicles and find the nearest vehicle 
}
};
static std::vector<Vehicle*> vv;
Put it into any of the typical OO scenarios used as examples:
Does an animal know about every other animal?
Does a car know about every other car?
Does a color know about every other color?
What you are asking is really opinion based, but I'm sure most people would say "no". You use some kind of manager class to control the instances.
In your case I'd have a Vehicle which knows it's location and a VehicleManager which knows about all the Vehicles. If you want to know what color a Vehicle is you ask the Vehicle. If you want to know where all the Red Vehicles are - you ask the VehicleManager.
Your solution has a combined Vehicle/VehicleManager which relies on a static collection of vehicles so you can only ever have one set. If you use two classes as I've described you can have multiple sets. e.g. Vehicles of different companies or trucks vs cars etc - sure there are other ways to do this as well, but your solution locks you in. Using 2 classes is much more flexible.
So to answer your last comment: do you think it's ok or is it a terrible design? - It is terrible design.

C++ difficulties accessing method from a deep inner class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have several classes in my project and some of those classes are the members of other ones. While manipulating the outer class, I would like to access some parameters of its member classes (which could also have their own member classes).
I guess this is not exactly what are "nested classes" in C++, since nested class are being declared within the declaration of the outer class. Then the nested class may not be accessed from the outside of the outer class (just a piece of information for me, to make sure I don't write garbage).
Let’s say I have an AnalogSensor class (handles the behavior of a real analog sensor). This class may have several handlers (one for ADC requests handling, one for filtering incoming data, one for data handling, and the last one for deadzone management).
class LinearSpace {
public:
// Getters & setters
private:
uint16_t min_val; // I'm working with embedded devices
uint16_t max_val; // Those are values used for linear interpolations
// purposes
};
class DataHandler {
public:
// Some useful methods
uint8_t map_raw_data(); // Converts the mapped adc_result (10 bits)
// value into an 8-bit, interpolated value
private:
LinearSpace input_space; // Two values spaces used for interpolation
// purposes
LinearSpace output_space;
};
class AnalogSensor{
public:
// "High-Level" methods like void send_adc_request(void);
// which relies on the internal ADC hander
private :
AdcHandler adc_handler;
DataHandler data_handler;
Deadzone deadzone;
DataFilter data_filter;
};
Each one of those handlers may rely (or not) on other subclasses, like value ranges (minimum value, maximum value) which has its own getters and setters (getmin, getmax, setmin, and setmax).
Here is an example of what I could end with in my project:
AnalogSensor mysensor
|
- dataHandler data_handler
|
- LinearSpace input_space
| |
| - min_val
| |
| - max_val
|
- LinearSpace output_space
|
- min_val
|
- max_val
Well, now let’s say I want to modify the minimum and maximuml value of a given range, directly from the AnalogSensor class. How should I do?
This requirement comes from the necessity to adjust those values for each calibration process (at runtime), as voltages and electronic measurement may vary with time / external conditions such as moisture, etc.
I found many ideas on the Internet:
Declare a class as friend (AnalogSensor is the friend of
AdcHandler and dataFilter, etc...)
Declare as much getters and setters inside AnalogSensor which are dedicated to target one specific range (there will be tens of them and I think it is pretty dirty).
Or using pointers to access the exact valueRange I want to modify (without
breaking encapsulation I hope) directly from AnalogSensor class.
In this particular case, I can do something like this:
mysensor.getDataHandlerPointer()->getInputSpacePointer()->set_min(my_new_value);
How would you do to access those values?
If you have tens of ranges to change and monitor, it may be wise to store them in (an) array(s), and refer to the ranges by index. i.e.:
struct my_s
{
enum RangeSpace { input_space, output_space, N_SPACES };
void setRange(RangeSpace id, int min, int max) { spaces_[id].setMinMax(min, max); }
// etc...
private:
LinearSpace spaces_[N_SPACES];
};
Such indexing will optimize nicely when using constants when calling, as in:
//...
my_s s;
int a = 0, b = 0;
//...
s.setRange(my_s::input_space, a, b);

Is there anyway in c++ to make a function of a class who's objects each do something different for that function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Just some background:
I am making a monopoly game and now I have to implement the actions of each space such as GO, properties (upgrading), chance, community chest, jail, etc.
I've considered making a different class for each space (but obviously that would be very time consuming). I believe there is also a way do to it with inheritance and pure virtual functions. Any way you guys can think that would make this a simpler process?
Thanks!
There are only a few different types of spaces:
properties
railroads
chance / community chest
utilities
other single ones like go, jail, parking, tax
For example you could have a Property class where each instance of the class has a different name/colour/price. You wouldn't have to make 22 different classes, just have 22 instances of the same class with different names.
Note that having class instances that represent spaces you can land on is only one way to implement a game like that. I'm pretty sure I wouldn't choose that option.
There are two ways you can make a function do different things given an object:
Differentiate the behavior based on the data of the object.
You could capture the differences in the various spaces using data.
enum SpaceType
{
GO, CHANCE, COMMUNITY_CHEST, // etc...
};
class Space
{
public:
void foo()
{
switch (spaceType)
{
case GO:
// DO stuff for GO
break;
case CHANCE:
// DO stuff for CHANCE
break;
// etc..
}
}
private:
SpaceType spaceType;
}
Differentiate the behavior based on the type of an object.
class Space
{
public:
virtual void foo() = 0;
};
class GoSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for GO
}
};
class ChanceSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for CHANCE
}
};
// Similarly for other classes.
Pick your method. Personally, I would pick the second method because the logic for each different type is put into their own functions, without the complications of what other types do.

How would you structure the class interactions in a physics engine? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a physics engine in C++ and I've come to a stop, namely how I should design the class hierarchy. What I'm specifically concerned about is the World and Body classes. Body should expose some details to World that World then can work on. But at the same time, I don't want users to be able to access all of those properties of Body. But I still want users of the engine to be able to change some things in a body. For example, its position. How would you structure this in terms of classes?
Define an interface (i.e. a pure virtual class) that specifies what functions you want exposed from Body. Have Body implement that inteface.
Allow that interface, and not Body to be used from World.
This pattern is called composition.
Recently, I've solved a similar problem by introducing a special interface for the restricted operations, and inheriting protectedly from it. Like this:
struct RestrictedBodyFunctions
{
virtual void step() = 0;
virtual Body& asBody() = 0;
};
struct Body : protected RestrictedBodyFunctions
{
static std::unique_ptr<Body> createInWord(World &world)
{
auto Body = std::unique_ptr<Body>{new Body()};
world.addBody(*body); // cast happens inside Body, it's accessible
return std::move(body);
}
std::string getName() const;
void setName(std::string name);
protected:
void step() override
{ /*code here*/ }
Body& asBody() override
{ return *this; }
};
struct World
{
void addBody(RestrictedBodyFunctions &body)
{
m_bodies.push_back(&body);
}
void step()
{
for (auto *b : m_bodies)
{
myLog << "Stepping << " b->asBody().getName() << '\n';
b->step();
}
}
private:
std::vector<RestrictedBodyFunctions*> m_bodies;
};
That way, users can create Body objects using createInWorld, but they only get a handle to (the public part of) Body, while the World gets its handle to RestrictedBodyFunctions.
Another option you have is to reverse the above idea - provide a restricted public interface PublicBody, and have Body derive from PublicBody. Your internal classes will use the full Body, while factory functions make sure only PublicBody-typed handles are available to the clients. This alternative is a more simple design, but provides less control over who can access the full functionality.

Differentiating between data class and logic class in agile [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've been reading an agile book about clean coding, mainly in Java and c#. Considering the concept of differentiating between a data class and a logic/object class. I have the following situation in c++, where I can't decide which variant is a clean code. I have a Plane class with some attributes and these attributes change when only one of them changes, so
First Method
class Plane3D {
public:
BBox bbox;
float l,w,h;
void setbbox(BBox bbox) {
this->bbox = bbox;
recalculateLWH();
}
void setLWH(float l, float w, float h) {
//set here
recalculateBBOX();
}
};
This makes sense to me, since to the user he is just calling one method and doesn't have to care about internal work of the class. but this is a violation for a data class, that it contains logic
Now the
Second method
class Plane3D {
public:
BBox bbox;
float l,w,h;
void setbbox(BBox bbox) {
this->bbox = bbox;
}
void setLWH(float l, float w, float h) {
//set here LWH
}
};
int main() {
BBox bbox;//init here
Plane plane;
plane.setBBox(bbox);
recalculateLWH(plane);
}
Now the second method actually separates the data class from the implementation but it increases the responsibilities of the class user and forces him to make an extra call. To my understanding the second method is the correct one from an agile POV, but I find the first method more logical to use.
I'd like to know which of the two methods would make more sense for you guys to undertsand and use
Regards
In this case I think you should prefer first method to second.
Your method calls should transform object from one correct state to another correct state. Using the second method after your setBBox(bbox); call your object moves to some incorrect state indeed.
But 'logic class way' can however take place in another situation.
Consider you should move plane:) from hangar to landing strip. Now it will be naturally to introduce new class named Tractor and use it like tractor.move(plane)