should a class manage its instantiated objects? [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 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.

Related

C++ basic architectural design [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 4 years ago.
Improve this question
I´m not sure about the right decision so I ask the community:
So the question is: is it better to model attributes through types or through attributes or is there even a third way?
Let´s say we have two balls - red and blue and I have to do something with them.
So the first idea was:
struct Ball
{
RGB color;
};
void food( Ball& ball)
{
if ball.color == RED ....
if ball.color == BLUE ....
}
I think you get it. But I want to get rid of the if(..) so I can changed this to
struct Ball
{
virtual RGB color() = 0;
}
struct RedBall : public Ball
{
RGB color() { return( RED); }
};
struct BlueBall : public Ball
{
RGB color() { return( BLUE); }
};
void foo( RedBall&) ...
void foo( BlueBall&) ....
I´m not sure if it is the proper way by creating new types (by inheritance or by using decorators) to depict program flow and behavior because this could quickly lead to huge class hierarchies.
It becomes even worse if I think about using these types with the visitor pattern, especially for decorated types.
What am I missing here ?
To have multiple versions of foo, that takes different colours of Ball seems completely wrong. I would argue that if you want to do that, you probably want a member function within Ball that does whatever foo does differently for the different colours of ball.
You can choose to implement that as a virtual function and have derived classes to represent each colour, or have a set of if-statements which are now internal to the Ball class, so "hidden" for others.
The idea with object orientation is to have objects that "do stuff", not just holders of properties (colour in this case), so the "most correct" way to solve this is to have the class itself know what objects of that kind should do.

Decouple visualization methods and application [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 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);
}
};

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.

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)

Proper object usage in a simple game setting [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Assuming that I wanted to make a simple dos-based game and I wanted to create some mobs, I've come up with the following rough object that I would need, and it looks something like this:
class createMob{
private:
int healthMax;
int healthCurrent;
int manaMax;
int manaCurrent;
int experiencePoints;
public:
void setHealth();
int getHealth();
void setCurrentHealth();
int getCurrentHealth();
void setMaxMana();
int getMaxMana();
void setCurrentMana();
int getCurrentMana();
int getExperience();
//etc etc functions truncated for space
};
My question is how do I use this? Assume that I create a simple constructor to take in a hp / mp / experience for a mob called "green slime" (final fantasy theme going on here). My basic goal is to create a monster with x / y /z attributes and set them based on what happens in combat... What would be the easiest way to do this and then clean up efficiently afterwards?
If you have two mobs in a fight, the fight is going to take longer than one turn, so one fight turn is going to need the following global function:
void fight(Mob &m1, Mob &m2, int fightstep);
Now this function can change properties of both mobs. Now if mobs are actually doing some actions to choose how the fight is going, you'll need something different:
void fight(Mob &m1, Mob &m2,
std::vector<Action> vec1, std::vector<Action> vec2,
int fightstep);
with the action being something like this:
enum Action { EDoNothing, EBash, ECastSpellXXXX ... };
Now the fight functions can use the interface of Mob class to do the changes.