Forming objects from a list to a new object - list

I have to create a train with locomotives and wagons. I created them and put them all in list, where I can give them an ID and sort them and such things.
My question is now if I can get some of them out of that list and form a new Object train with them, or is it better to just implement them directly without touching the list?

This is a little vague, what type of data are these "locomotives" and "wagons"? How is that data going to be manipulated?
In general, if you have a complex possibly nested object it's better to create a Class for it. If you create a Train class, it can contain as an attribute a list of locomotives and wagons, which themselves are another Object. And better yet, you can define class specific functions to manipulate a Train's locomotives and wagons.

Related

How to partly initialize c++ objects when I don't need all values from the database?

I’m trying to cut down on the amount of network queries in my c++ program (to increase speed), and when displaying search results, I don’t want each (of the sometimes thousands) of objects found in the search to initialize themselves completely from the database when I only need to display part of this information.
It is much faster to perform one bigger query where I get all the information I want to display about the objects at once in the query (for example, for each object/row I select the id, the name and the location), passing them to a bigger constructor, and letting all other members be default values. Previously, and in other cases where I need the complete object, I just pass the ID to the object, then call initializeFromDatabase() directly to set all the other values.
//current solution (problem is, I might need many constructors like this for different purposes)
auto *myobject = new MyObject(345, "ObjectName", "Europe");
//no further (costly) initialization since I only need the following 2 values for my search results.
myobject->getName();
myobject->getLocationName();
//prevous solution (resulting in too many queries)
auto *myobject = new MyObject(345);
myobject->initializeFromDatabase();
myobject->getName();
myobject->getLocationName();
//I could also query the other 30 or so members here, everything is set.
This doesn’t feel like good practice though, I would need other custom constructors for say, another search window displaying other kinds of data about the objects.
Are there any general best practices / a suitable design pattern to solve this sort of problem? Should I create a “Search object” that is its own class and that can then be used to create the complete object when needed? Or always initialize with only the database ID (setting a flag that the object is not initialized yet) and use the setters I need?
I found that a solution to this would be to use some sort of Lazy Loading, since I want to quickly load part of the object for the list, then load all of it if a user clicks on one of the objects. For example, a Virtual Proxy or the Ghost Design pattern would be suitable. I simply create a proxy object for displaying the search results (and for other lists in the program) that can create the full object on demand. Every proxy object has one constructor so I avoid the problem of using lots of different constructors for different purposes.
See Chapter 11 of Patterns of Enterprise Application Architecture by Martin Fowler (published by Addison-Wesley Professional, 2002)

Future-proofing data types(i.e creating structs with only one member in hopes they can be expanded later, when needed)

Say I want to create a list of variables/objects to store something very specific(say the coordinate for where an enemy needs to spawn in a videogame), at first I would only need a simple point in space to store this information but later on I may want to add the enemy type and other data specific to each element of this list. Is it good practice to write a whole new class or struct with only just the initial data member I need in hopes that whenever I need to update the list with more data per element I can just add members to this previously redundant struct/class? Furthermore, is packaging an already existing type into a new one in the spirit of being more descriptive something that actually helps code readability?
Sounds like a classic case for some good old object orientated programming.
So the idea would basically be that you have your simple struct/class with, as mentioned in your example, coordinates. If you would want to add another enemy with some extra attributes to be stored you would go ahead and create a new class/struct that inherits from the very basic class. That way you get all the attributes the basic class had in your new class plus you can define new ones.
That way you have a good structure in your code and it is easy to understand what is going on. Scalability and reusability also profit greatly from this, which is why this concept is state-of-the-art.
This might sound a little confusing at first, but I recommend to read up on inheritance and object oriented programming in general. I promise it is not too hard once you get used to the thinking patterns.

List of subclass "master copies", looking for a better design

I recently worked on a small game project where the player would be granted a random item at a certain point. The items (about 50 or so) were implemented as sub-classes of a virtual Item interface. We needed a way to select one of those items randomly and give an instance of the specific class to the player.
Our solution was to create some container (e.g. std::list) and insert an instance of each item we implemented. The item implementations had to provide a copy constructor, so that we could just create a copy for the player who gets the item. Voilà!
The downside is clear: it's very easy to forget inserting an item, and being careless with the copy constructors can lead to bugs that are not so easy to track. Since it was prototype code we didn't bother too much, but I wonder if there is a prettier way. An ideal solution would include:
Automatic "registering" of items, somewhere.
A way to choose one item at random and instantiate it.
No need for writing copy constructors for each item.
Thanks for your hints and suggestions!
Daerst
You can create a factory to create items. The factory will then also register the create item in the container. I'd like to use shared pointer for players! But that'd be up to you.
This way you can ensure that items will be created through a single interface. And also the common logic for inserting items etc. is implemented at a single place.
There are details that are not clear in your question. For example, based on my interpretation of your question it would seem that you are hard coding the specifics of your items? Based on the assumption that you're current prototype is hard coding the details of your items for your game I would:
Separate the content from the code - This is important because changing content values will require you to recompile, or more importantly, expansion of the total number of items will soon become burdensome and error prone.
Create a generic class that represents an item with all of the appropriate fields necessary to populate this item class with the relevant details of the item.
2A. If your items do not have similar properties, you could use some sort of self-describing array of the custom aspects of the item. For example, Item A is unique and has a flavour property. You would have a a two dimensional array [1][2] with it's values being [1][1] = flavour [1][2] = blueberry.
Create a class that acts as a container for items.
In the container class, implement a method to instance a random item (pulling the details about the item from the database or other storage mechanism), and adding it to the containers collection of "loaded items" - effectively "registering" it. The two obvious benefits to having this container class is that once an item is loaded, and if you then choose another random item that happens to be one already loaded, you don't have to load it again and secondly, you are using less memory until the entire item set has been loaded.
In the container class, implement a method to copy an instanced item to the player class. - OR - create an interface in the container class that your player class implements to request a new random item - which would then call upon the method to instance a random item.
Hope this helps in your brainstorming!
Add the items to the vector right inside the constructor of the Item class. That way you won't need to add every single item "by hand", they'll be added upon creation.
Instead of copying the items, make them singleton classes and instead of 'giving' the user an item, just use a pointer to a place inside your vector.
That being said, your problem is strictly connected with the bad design of the game. Items shouldn't be derived classes, but instances of a generic item class. But since other people already mentionned it, I don't think typing it once more would be any help to you :)

How to create artificial nodes in QAbstractItemModel for QTreeView

my question is about Qt and its QAbstractItemModel.
I have a map of strings and doubles (std::map<stringclass, double>) which I would like to present in a Qt widget. While I could use QTableView for that, I would like to exploit the fact that the keys of the map are of form "abc.def.ghi" where there can be multiple strings that can start with "abc.def" and even more that start with "abc".
So I would like to setup a tree data model to present the items in a QTreeView like
(-) abc
|--(-)def
|--ghi 3.1415
|--jkl 42.0815
|--(+)pqr
|--(+)xyz
The keys of my std::map are the leaves of the tree, where all other nodes would be temporary and auxillary constructs to support the folding for user convenience.
Unfortunately, the methods rowCount, index, columnCount, and data have const-modifiers, so I cannot simply setup a auxillary data structure for the headers inside my QAbstractItemModel derivate and change that data structure in there.
What would be the best practice for that? Should I setup another class layer between my std::map and the QAbstractItemModel or is there a smarter way to do this?
Edit 1: The std::map can change while the QTreeView is shown and used, so the auxillary nodes might be thrown away and reconstructed. My assumption is that the best way to handle this is to restructure the QAbstractItemModel - or should I simply throw that model away and assign a newly constructred one to the QTreeView? In that case I could set-up all nodes within the constructor without being bothered by the const-ness of the methods, I guess.
I would parse the map and create a tree data structure based on it. Make sure you sync the model when you change the map.
If this sync step gets too complicated you might want to hold your data in a tree structure from the start and convert to a map when necessary.
Parsing the map on the fly in the model functions seems like a bad idea to me, you'd want these functions to be as fast as possible.
I don't see how const-modifiers would really be an issue.
What members of your QAbstractItemModel derivate would you want to modify when rowCount, index, columnCount and data methods are called ? You may very well store a reference to your map, and compute everything from it. No need to modify the map itself to extract the needed information (as far as i can tell !).
EDIT after EDIT1 and comments :
If your map is bound to be modified, use it as your base structure in your own class.
If you can't keep a reference to your map because the model's lifetime might exceed the map's, use smart pointers to make sure it does not happen.

C++ class design from database schema

I am writing a perl script to parse a mysql database schema and create C++ classes when necessary. My question is a pretty easy one, but us something I haven't really done before and don't know common practice. Any object of any of classes created will need to have "get" methods to populate this information. So my questions are twofold:
Does it make sense to call all of the get methods in the constructor so that the object has data right away? Some classes will have a lot of them, so as needed might make sense too. I have two constrcutors now. One that populates the data and one that does not.
Should I also have a another "get" method that retrieves the object's copy of the data rather that the db copy.
I could go both ways on #1 and am leaning towards yes on #2. Any advice, pointers would be much appreciated.
Ususally, the most costly part of an application is round trips to the database, so it would me much more efficient to populate all your data members from a single query than to do them one at a time, either on an as needed basis or from your constructor. Once you've paid for the round trip, you may as well get your money's worth.
Also, in general, your get* methods should be declared as const, meaning they don't change the underlying object, so having them go out to the database to populate the object would break that (which you could allow by making the member variables mutable, but that would basically defeat the purpose of const).
To break things down into concrete steps, I would recommend:
Have your constructor call a separate init() method that queries the database and populates your object's data members.
Declare your get* methods as const, and just have them return the data members.
First realize that you're re-inventing the wheel here. There are a number of decent object-relational mapping libraries for database access in just about every language. For C/C++ you might look at:
http://trac.butterfat.net/public/StactiveRecord
http://debea.net/trac
Ok, with that out of the way, you probably want to create a static method in your class called find or search which is a factory for constructing objects and selecting them from the database:
Artist MJ = Artist::Find("Michael Jackson");
MJ->set("relevant", "no");
MJ->save();
Note the save method which then takes the modified object and stores it back into the database. If you actually want to create a new record, then you'd use the new method which would instantiate an empty object:
Artist StackOverflow = Artist->new();
StackOverflow->set("relevant", "yes");
StackOverflow->save();
Note the set and get methods here just set and get the values from the object, not the database. To actually store elements in the database you'd need to use the static Find method or the object's save method.
there are existing tools that reverse db's into java (and probably other languages). consider using one of them and converting that to c++.
I would not recommend having your get methods go to the database at all, unless absolutely necessary for your particular problem. It makes for a lot more places something could go wrong, and probably a lot of unnecessary reads on your DB, and could inadvertently tie your objects to db-specific features, losing a lot of the benefits of a tiered architecture. As far as your domain model is concerned, the database does not exist.
edit - this is for #2 (obviously). For #1 I would say no, for many of the same reasons.
Another alternative would be to not automate creating the classes, and instead create separate classes that only contain the data members that individual executables are interested in, so that those classes only pull the necessary data.
Don't know how many tables we're talking about, though, so that may explode the scope of your project.