advice on an oo planing - c++

I am trying to develop an object oriented representation of a finite element model. The finite element model consists of some output files(outputs of a commercial Finite element program) in binary format which keep certain data related to the finite element model (for people who are not in the field, these data correspond to nodes of the model( coordinates of the nodes), elements of the model, element connectivity for the element representations(which elements are associated with which nodes) and element matrix information). These data could also be represented generally as some vectors of ints and double and some other array structure if you call so.
I was thinking of making a general class FeModel and associating the above mentioned files as members of this class and work this way, of course these files would also be objects representing these files. However, the files that keep the information are not a part of the FeModel class that I was thinking on, at least conceptually. Since the idea does not relate to the real world representation, I thought that there should be a better way. Those files are just there to keep the information.
I am now thinking on the option of just reading the necessary information from these files in the FeModel class by creating suitable member functions and build what I want this way so that the interface is more or less a minimal one. However, on the other hand dividing this task into different classes representing the above mentioned files and using those as members in the FeModel class does not look also like a bad option to me. What are the decision criteria in these situations? I am aware of the fact that a problem could be solved in many different ways but are there some sort of guidelines to follow in similar kinds of cases where one hesitates between some options?
Greetz,
U.

My that's a bit of a wall of text. It could use a bit of filtering/rewriting.
As I understand it you have several files representing your 3D elements etc.
I nice OO way of doing it (at least in my mind) would be to have a separate class for each type of file you want to load, pass the filename in the constructor and load in the data, and have accessible members to access the data.
But without further information, structure to what you're asking it's a bit difficult to say.

You probably want to read about SOLID principles of OOP.
In my opinion, it's all about making you design less fragile in the face of changes. In few words, you should strive to the design which is changes-friendly: minor changes domain in model should be reflected by minor and local changes in the design and the implementation.
Don't forget that C++ is not OO-language, but rather language that supports several paradigms (including OO) and other paradigms could fit better to task at hand. If you have access to Bjarne Stroustrup excellent "The C++ Programming Language (Special Edition)", read through Part IV ("Design using C++") to get the idea of roles of classes and other C++ concepts.

An OO solution focuses on behavior, not data. You haven't told us what behaviors you need so we can't help with an OO solution.
That said, find your invariants and create a class for each related set of invariants and you should end up with a decent modular solution.
I suggest you read the book Object-Oriented Design Heuristics by Arthur Riel.

Related

SIMD and object-oriented programming

I have been reading about SIMD for some time and I am going through the slides over at Insomniac Games.
I like the idea and I am certainly open to making my code run more efficiently but I am just not clear how to get started with SIMD in terms of higher level code design.
For instance, let's assume that I am using a language low-level enough to let me know what the memory layout of arrays or classes is, e.g. C++.
If I now have a class such as User with attributes user_id or user_name, as a person modelling the domain that I am in, I know that I will be able to put users into hashmaps, or perhaps into arrays, vectors, or maybe sets, all depending on a particular use-case that a given User is needed in.
That is, I have a reusable User object and what data structure these objects are in is something independent of the User class's own internal structure.
Now, all the SIMD guides say, and I understand why, that instead of arrays-of-structures I should be using structures-of-arrays.
This makes sense as far SIMD instructions go but I cannot find a way to reconcile it with the fact that I am not starting with an array-of-structures that I can easily turn into a structure-of-arrays. Instead, I am starting with User. Sometimes users - in the sense of references to User objects - will be in arrays, sometimes in hashmaps, sometimes in other containers.
But this is not a scenario that online guides mention - all of them just say to turn AOS into SOA and again, I understand why, it is just that it is not a starting position of mine.
I feel that there is a gap that I just cannot make a leap over because I cannot find more complex examples. For instance, maybe I should keep user-related data in, say, two places, one is the User object for general ad-hoc access and another in SOA for SIMD instructions?
Put more generally, how does one model more object-oriented design into SIMD?
Or do people designing entire applications with SIMD in mind do not adhere to such OO concerns at all, instead opting for more data-oriented design?
Or perhaps SIMD is limited to selected modules in one's codebase and such a translation between OOP and SIMD takes place in runtime when needed (i.e. the actual data is kept both in User objects and in SOA and there is manual code to keep them in sync).
I would appreciate it if people with SIMD experience could shed more light on it from a higher level perspective. Thank you.

struggling with Object Oriented class design

I'm comming from an scientific background and I'm having trouble to think object oriented. I'm always thinking of functions not objects.
For example I've got a Dataset containing multiple 2D arrays and I like to extract Regions of Interest out of these arrays. So my first Design was something like a RoIFinder class to whom I pass a reference to the Dataset object. The RoIFinder object did its magic and returned the RoI's.
But this gives me a bad feeling since it looks more like a function than an object.It's more like a Blackbox. But I have no Idea how it is done properly.
How would you do something like that?
OO is not a silver bullet. Do your work in whichever way it seems to be correct from the different points of view: problem decomposition, efficiency, code simplicity, testing, etc.
Do not make the code look in OO way if you don't need to. The OO is about simplification the life when the problem is too complex, not for making simple problems solved in a complicated way.
Specifically for your problem, I see nothing bad in your approach. It possibly doesn't use some advanced techniques, so what?
To me it sounds like in the specific situation you describe, this could be a fine OO design.
OO in brief is about bundling together
state
behaviour
(identity).
Whenever you have data which represents the state of (a part of) the system, and you have behaviour tied to (typically manipulating) that data, you have a candidate for an object. Optionally, these objects may also have an identity, but this may not be always necessary.
If you potentially have multiple different criteria to pick regions of interests out of the Dataset, you may implement these as distinct *Finder classes, implementing a common base interface. There you have an OO class hierarchy! From then on, the Finders can even be used as interchangeable Strategies in your code.
The alternative would be to put the finder functionality in the Dataset. This might be OK if you are absolutely sure you won't have more different criteria to extract regions. Even then, your Dataset has two distinct responsibilities, which is usually not a good idea. It is better to have each class be responsible for one thing, and do it well.
We don't know what you are supposed to do with the data in the arrays - there may be some possibility to find more abstractions there and build some OO types and objects on these too.
Note though, that these all are just possibilities. Implement them only if they are actually useful (for solving problems, simplifying your code, or - last but not least - helping you gain practical experience with new concepts).
What you've done is probably better than the obvious OO approach of adding a find_roi() to the Dataset class itself. Why? Because it sounds like you've created the RoIFinder functionality based only on the public API of Dataset. Keeping Dataset simpler is also good. The STL (well these days it's just part of the Standard library) has examples of this in the way algorithms such as sort are applicable to multiple containers, rather than each container have a sort member function (although in the case of list optimisation opportunities leads it to implementing its own version). The STL also has std::string which controvertially embeds a lot of functionality that could have been factored out - in my opinion it is well designed, prioritorising convenient and elegant usage which is important in such a ubiquitous class which is so frequently and heavily operated on. So, pick what suits the situation. Anyway, there's no reason to put the RoIFinder into a class if it could equally be just a function, but if you've found some state (i.e. data members) that are convenient to preserve, or it helps usability in some other way, then that's a good enough reason to stick with your object.
Your 2D array can be implemented as a matrix class. One object
A region of interest is another class.
Getting a region of interest out of a matrix is a method.
"Iterators" into your matrices are classes.

C++ Beginner game programming: Keeping track of objects, inventory lists, arrays of different amnts of object/characters, etc

I was just playing an old SNES RPG (Secret of Mana, if anyone cares) and was wondering a few general things about game programming.
Sorry for some of the brain-dead questions, I'm really a beginner. :)
These questions are quite general, but use SNES-style RPGs as a "template" to get an idea of what I mean:
How do games keep track of all the objects, triggered events, etc in its "world"? For example, how does it keep track of which treasure chests have already been opened, which doors are locked, which story events have already triggered?
Does it basically create an array of elements each corresponding to a chest/door/event/etc and "mark" each (change its value from 0 to 1) when it has been opened/triggered? If there are multiple approaches, what are they?
How are "variable lists" handled? Ie, if you have a game when you can have a huge inventory of objects (ie: armor, swords) and have X of each object, how is this done?
My guess: have a struct that has a big array with a spot for every possible object (an array of X ints, where X is number of possible objects to own) where each element's value represent how many of that object you have, and then have a giant enum of every object so that an object is matched to a corresponding index, and access it, like: numberOfSwords = inventory[SWORDS] where SWORDS is part of an enum and has some integer number associated with it. How close am I?
How about the case where the number of objects can vary? Ie, if I have a game where I have some amount of enemies on the screen and they can get killed / give birth to new enemies at any point, it would seem to me like I would need an array of "enemy" objects to loop through and process, but that the number of elements would vary at any one time. What is the usual approach to this? Linked lists?
Any help / hint / pointers are really appreciated.
In a very basic manner your answers are not too far off, things could be done the way that you mention them. However space and processing power can come into play so instead of an array of bools to track which treasure chests or how far along the chain of events you are you may want to slim it down to bits being on and off and use the bitwise operators for masking to see where you are in a storyline or whether or not to show the treasure chest you are about to display as opened or close.
For inventories, instead of tracking how many of each item a player has it may be better to have a base item for everything a player can pick up; weapons, armor and even money. Then you could make a linked list of just the items the player has. Use the Enum for the item as you mentioned and then the quantity of that item. This would allow for sorting of things and would also only keep in memory the items the player's character(s) actually have/has. You could extend this data structure to also track if the item is equipped. You could likely keep more generic what the item does sort of information in an items table.
The enemies would likely be a bit more complicated as you need to do a few more things with them. A linked list here though is still likely your best bet. That way removal of an object form the list would be a mite bit easier (can simply remove the link and the like when a player kills them or add in a new enemy wherever needed in the list.)
Honestly there is no one answer and it can depend on quite a few things. The best way is really to simply try it out.. For a simple 'what if I do this for this' it really does not end up taking all that long to give it a whirl and see how far you get. If you start running into issues you can start to consider other options :)
Hope this helps.
Edit: Just wanted to add in a link to www.codesampler.com. Generally more DirectX oriented tutorial sites but as a beginner it can start you thinking or give you a set of places to start. As an added bonus alot of the DirectX SDK examples/samples started to be formatted very much like how this site's tutorials are done. Can help ease you into the whole thing.
This is a pretty advanced question for a beginner.
I'd like to echo In Silico's response that you should learn C++ language basics before you tackle this subject.
To give you a place to start, you should know about container classes (Linked Lists, Vectors, HashTables/Dictionaries, Queues etc) and how they work. Since the Standard Template Library (STL) is pretty standardized, it would be a good place for a beginner to start.
You should also know about inheritance and how to build a hierarchy of classes.
For example, you asked about inventory in a role playing game:
I'd start by defining an InventoryItem class that defines or sets up an interface for all of the code necessary for an item to participate in your inventory system.
Something like:
class InventoryItem
{
private:
std::string description; // A description of the item
bool inInventory; // True if in the players inventory, false if on the ground etc...
int weight; // How much the item weighs
int size; // How much space the item takes in inventory
// etc...
};
In the InventoryItem class you'd also define the member functions and data needed for InventoryItem to be placed in your container class of choice.
The same sort of thing holds true for triggered items, things on the ground etc. They're typically kept in a container class of some sort.
The STL containers will take care of the variable sizes of the containers mentioned in the last part of your question(s).
vector is a good place to start for a general list of items.
HashTables/Dictionaries are good for looking things up with a key.
I hope this is enough to get you started. Good luck.
In addition to James' excellent post, some keywords for you to google for
Data structures
linked list
doubly linked list
queue
for the theory of dynamic memory management.
Also, let me share my standard recommended links for people asking for aid on basic c++:
Full scale tutorial on c++
C++ Language Reference (including STL)
ANSI C Language reference for all those pesky C stuff that C++ keeps using
Your question is not specific for "games programming". You are asking how arbitrary data is organized and stored in bigger programs. There is no definite answer to this, there are lots of different approaches. A common general approach is to make a data model of all the things you want to store. In C++ (or any other languages with object oriented capabilities), one can create an object oriented class model for this purpose. This introduction to C++ contains a complete tutorial on object oriented modeling in C++.
Lots of applications in general use a layered approach - the data model is one layer in your application, separated from other layers like a presentation layer or application ("game") logic.
Your data modeling approach will have to deal with persistency (that means, you want to store all your data on disk and reload it later). This question was asked earlier here on SO. This fact will give you some restrictions, for example, on the use of pointers.
EDIT: if your data model reaches a certain complexity, you might consider using a (lightweight) database, like SQLlite, which has a C/C++ api.
Finally, here is a link that might give you a good start, seems to fit exactly on your question:
http://www.dreamincode.net/forums/topic/26590-data-modeling-for-games-in-c-part-i/
Regarding Question #1, I concur with James and others on using a database that stores the persistent state of your game objects.
Regarding questions #2 and #3, about variable numbers of objects and objects that need frequent updating: I'd suggest maintaining a registry of objects that need updating for each game "cycle" (most games operate on cycles -- loops, if you like, though a modern game uses many loops spawned as separate threads).
For instance, every time you introduce a new enemy or other object that needs to be updated to respond to the current situation or behave in a certain way, you register that object in a list. Each cycle, you iterate through your current list of updateables (probably based on some priority scheduling mechanism), and update them accordingly.
But the particular data structure you use will depend on your program. Linked lists are a valid foundation structure, but in all likelihood you'll want to use a custom compound structure that meets your particular needs. Your approach may combine any number of classic data structures to achieve the best result in performance and effect.
Considering this, I can't emphasize enough the importance of studying advanced data structures before you tackle any sort of serious programming project. There are scores of great books on the topic and you'd do well to study them. Here's a link to a tolerable overview of the classic data structures: http://randu.org/tutorials/c/ads.php

How should I design a mechanism in C++ to manage relatively generic entities within a simulation?

I would like to start my question by stating that this is a C++ design question, more then anything, limiting the scope of the discussion to what is accomplishable in that language.
Let us pretend that I am working on a vehicle simulator that is intended to model modern highway systems. As part of this simulation, entities will be interacting with each other to avoid accidents, stop at stop lights and perhaps eventually even model traffic enforcement with radar guns and subsequent exciting high speed chases.
Being a spatial simulation written in C++, it seems like it would be ideal to start with some kind of Vehicle hierarchy, with cars and trucks deriving from some common base class. However, a common problem I have run in to is that such a hierarchy is usually very rigidly defined, and introducing unexpected changes - modeling a boat for instance - tends to introduce unexpected complexity that tends to grow over time into something quite unwieldy.
This simple aproach seems to suffer from a combinatoric explosion of classes. Imagine if I created a MoveOnWater interface and a MoveOnGround interface, and used them to define Car and Boat. Then lets say I add RadarEquipment. Now I have to do something like add the classes RadarBoat and RadarCar. Adding more capabilities using this approach and the whole thing rapidly becomes quite unreasonable.
One approach I have been investigating to address this inflexibility issue is to do away with the inheritance hierarchy all together. Instead of trying to come up with a type safe way to define everything that could ever be in this simulation, I defined one class - I will call it 'Entity' - and the capabilities that make up an entity - can it drive, can it fly, can it use radar - are all created as interfaces and added to a kind of capability list that the Entity class contains. At runtime, the proper capabilities are created and attached to the entity and functions that want to use these interfaced must first query the entity object and check for there existence. This approach seems to be the most obvious alternative, and is working well for the time being. I, however, worry about the maintenance issues that this approach will have. Effectively any arbitrary thing can be added, and there is no single location in which all possible capabilities are defined. Its not a problem currently, when the total number of things is quite small, but I worry that it might be a problem when someone else starts trying to use and modify the code.
As one potential alternative, I pondered using the template system to achieve type safe while keeping the same kind of flexibility. I imagine I could create entities that inherited whatever combination of interfaces I wanted. Using these objects would entail creating a template class or function that used any combination of the interfaces. One example might be the simple move on road using just the MoveOnRoad interface, whereas more complex logic, like a "high speed freeway chase", could use methods from both MoveOnRoad and Radar interfaces.
Of course making this approach usable mandates the use of boost concept check just to make debugging feasible. Also, this approach has the unfortunate side effect of making "optional" interfaces all but impossible. It is not simple to write a function that can have logic to do one thing if the entity has a RadarEquipment interface, and do something else if it doesn't. In this regard, type safety is somewhat of a curse. I think some trickery with boost any may be able to pull it off, but I haven't figured out how to make that work and it seems like way to much complexity for what I am trying to achieve.
Thus, we are left with the dynamic "list of capabilities" and achieving the goal of having decision logic that drives behavior based on what the entity is capable of becomes trivial.
Now, with that background in mind, I am open to any design gurus telling me where I err'd in my reasoning. I am eager to learn of a design pattern or idiom that is commonly used to address this issue, and the sort of tradeoffs I will have to make.
I also want to mention that I have been contemplating perhaps an even more random design. Even though I my gut tells me that this should be designed as a high performance C++ simulation, a part of me wants to do away with the Entity class and object-orientated foo all together and uses a relational model to define all of these entity states. My initial thought is to treat entities as an in memory database and use procedural query logic to read and write the various state information, with the necessary behavior logic that drives these queries written in C++. I am somewhat concerned about performance, although it would not surprise me if that was a non-issue. I am perhaps more concerned about what maintenance issues and additional complexity this would introduce, as opposed to the relatively simple list-of-capabilities approach.
Encapsulate what varies and Prefer object composition to inheritance, are the two OOAD principles at work here.
Check out the Bridge Design pattern. I visualize Vehicle abstraction as one thing that varies, and the other aspect that varies is the "Medium". Boat/Bus/Car are all Vehicle abstractions, while Water/Road/Rail are all Mediums.
I believe that in such a mechanism, there may be no need to maintain any capability. For example, if a Bus cannot move on Water, such a behavior can be modelled by a NOP behavior in the Vehicle Abstraction.
Use the Bridge pattern when
you want to avoid a permanent binding
between an abstraction and its
implementation. This might be the
case, for example, when the
implementation must be selected or
switched at run-time.
both the abstractions and their
implementations should be extensible
by subclassing. In this case, the
Bridge pattern lets you combine the
different abstractions and
implementations and extend them
independently.
changes in the implementation of an
abstraction should have no impact on
clients; that is, their code should
not have to be recompiled.
Now, with that background in mind, I am open to any design gurus telling me where I err'd in my reasoning.
You may be erring in using C++ to define a system for which you as yet have no need/no requirements:
This approach seems to be the most
obvious alternative, and is working
well for the time being. I, however,
worry about the maintenance issues
that this approach will have.
Effectively any arbitrary thing can be
added, and there is no single location
in which all possible capabilities are
defined. Its not a problem currently,
when the total number of things is
quite small, but I worry that it might
be a problem when someone else starts
trying to use and modify the code.
Maybe you should be considering principles like YAGNI as opposed to BDUF.
Some of my personal favourites are from Systemantics:
"15. A complex system that works is invariably found to have evolved from a simple system that works"
"16. A complex system designed from scratch never works and cannot be patched up to make it work. You have to start over, beginning with a working simple system."
You're also worring about performance, when you have no defined performance requirements, and no problems with performance:
I am somewhat concerned about
performance, although it would not
surprise me if that was a non-issue.
Also, I hope you know about double-dispatch, which might be useful for implementing anything-to-anything interactions (it's described in some detail in More Effective C++ by Scott Meyers).

More on the mediator pattern and OO design

So, I've come back to ask, once more, a patterns-related question. This may be too generic to answer, but my problem is this (I am programming and applying concepts that I learn as I go along):
I have several structures within structures (note, I'm using the word structure in the general sense, not in the strict C struct sense (whoa, what a tongue twister)), and quite a bit of complicated inter-communications going on. Using the example of one of my earlier questions, I have Unit objects, UnitStatistics objects, General objects, Army objects, Soldier objects, Battle objects, and the list goes on, some organized in a tree structure.
After researching a little bit and asking around, I decided to use the mediator pattern because the interdependencies were becoming a trifle too much, and the classes were starting to appear too tightly coupled (yes, another term which I just learned and am too happy about not to use it somewhere). The pattern makes perfect sense and it should straighten some of the chaotic spaghetti that I currently have boiling in my project pot.
But well, I guess I haven't learned yet enough about OO design. My question is this (finally. PS, I hope it makes sense): should I have one central mediator that deals with all communications within the program, and is it even possible? Or should I have, say, an abstract mediator and one subclassed mediator per structure type that deals with communication of a particular set of classes, e.g. a concrete mediator per army which helps out the army, its general, its units, etc.
I'm leaning more towards the second option, but I really am no expert when it comes to OO design. So third question is, what should I read to learn more about this kind of subject (I've looked at Head First's Design Patterns and the GoF book, but they're more of a "learn the vocabulary" kind of book than a "learn how to use your vocabulary" kind of book, which is what I need in this case.
As always, thanks for any and all help (including the witty comments).
I don't think you've provided enough info above to be able to make an informed decision as to which is best.
From looking at your other questions it seems that most of the communication occurs between components within an Army. You don't mention much occurring between one Army and another. In which case it would seem to make sense to have each Mediator instance coordinate communication between the components comprising a single Army - i.e. the Generals, Soldiers etc. So if you have 10 Army's then you will have 10 ArmyMediator's.
If you really want to learn O-O Design you're going to have to try things out and run the risk of getting it wrong from time to time. I think you'll learn just as much, if not more, from having to refactor a design that doesn't quite model the problem correctly into one that does, as you will from getting the design right the first time around.
Often you just won't have enough information up front to be able to choose the right design from the go anyway. Just choose the simplest one that works for now, and improve it later when you have a better idea of the requirements and/or the shortcomings of the current design.
Regarding books, personally I think the GoF book is more useful if you focus less on the specific set of patterns they describe, and focus more on the overall approach of breaking classes down into smaller reusable components, each of which typically encapsulates a single unit of functionality.
I can't answer your question directly, because I have never used that design pattern. However, whenever I have this problem, of message passing between various objects, I use the signal-slot pattern. Usually I use Qt's, but my second option is Boost's. They both solve the problem by having a single, global message passing handler. They are also both type-safe are quite efficient, both in terms of cpu-cycles and in productivity. Because they are so flexible, i.e. any object and emit any kind of signal, and any other object can receive any signal, you'll end up solving, I think, what you describe.
Sorry if I just made things worse by not choosing any of the 2 option, but instead adding a 3rd!
In order to use Mediator you need to determine:
(1) What does the group of objects, which need mediation, consist of?
(2) Among these, which are the ones that have a common interface?
The Mediator design pattern relies on the group of objects that are to be mediated to have a "common interface"; i.e., same base class: the widgets in the GoF book example inherit from same Widget base, etc.
So, for your application:
(1) Which are the structures (Soldier, General, Army, Unit, etc.) that need mediation between each other?
(2) Which ones of those (Soldier, General, Army, Unit, etc.) have a common base?
This should help you determine, as a first step, an outline of the participants in the Mediator design pattern. You may find out that some structures in (1) fall outside of (2). Then, yo may need to force them adhering to a common interface, too, if you can change that or if you can afford to make that change... (may turn out to be too much redesigning work and it violates the Open-Closed principle: your design should be, as much as possible, open to adding new features but closed to modifying existent ones).
If you discover that (1) and (2) above result in a partition of separate groups, each with its own mediator, then the number of these partitions dictate the number of different types of mediators. Now, should these different mediators have a common interface of their own? Maybe, maybe not. Polymorphism is a way of handling complexity by grouping different entities under a common interface such that they can be handled as a group rather then individually. So, would there be any benefit to group all these supposedly different types of mediators under a common interface (like the DialogDirector in the GoF book example)? Possibly, if:
(a) You may have to use a heterogeneous collection of mediators;
or
(b) You envision in the future that these mediators will evolve (and they probably will). Hence providing an abstract interface allows you to derive more evolved versions of mediators without affecting existent ones or their colleagues (the clients of the mediators).
So, without knowing more, I'd have to guess that, yes, it's probably better to use abstract mediators and to subclass them, for each group partition, just to prepare yourself for future changes without having to redesign your mediators (remember the Open-Closed principle).
Hope this helps.