How do I avoid "coupling" in OOP - c++

OK, I'm not sure coupling describes truly my problem. The problem is, I'm creating my own 3d game engine based on ogre. I'm also using a physic library, PhysX, but since I need to create an abstraction layer between my main engine code and PhysX - so just in case we could use another physic engine - I decided to create a wrapper, Quantum.
So ogre have an Entity class which will control the entity on the screen
PhysX also have a PxActor class which contains the informations about the actor position in the PhysX works.
The quantum wrapper will have a QEntity class which will act as a layer between the engine and PhysX
Finally, the engine will have an Entity class which will have two members at least, the ogre entity object and the quantum entity. On each update() it will ask the QEntity what's up and update the ogre entity position.
Spot the problem? 4 classes for one entity? And remember that we need to access all four entities at least 60 times/s! So what about data partitioning? Not really optimised. Besides, there might be more classes, one for the AI,  one for the scripting engine...

Using objects of multiple classes to represent the same thing in multiple contexts is not a bad thing in itself. In fact, it would probably be worse if you had used the same object in all these contexts - for example, through some creative use of multiple inheritance.
Your QEntity class already does decoupling for you - as long as you program to its interface, and does not let classes specific to PhysX "stick out" from the interface of QEntity*, you are good.
It looks like your project introduces coupling in the "bridge" classes, which is exactly where it belongs. As long as you keep it there, your design would not have a coupling problem.
As far as 60 FPS goes, don't worry about it too much at the design stage. As long as there are no lengthy chains of responsibility relying on virtual functions, your compiler should be able to do a good job optimizing it for you.
* for example, QEntity shouldn't accept parameters or return objects that are specific to PhysX, except in a constructor that creates a "wrapper".

Related

Should I seperate model classes or have them as a single unit?

My game logic model consists of multiple connected classes. There are Board, Cell, Character, etc. Character can be placed (and moved) in Cell (1-1 rel).
There are two approaches:
Make each class of model implement interfaces so that they can be mocked and each class can be tested independently. It forces me to make implementation of each class to not rely on another. But in practice it's hard to avoid Board knowing about Cells too much and Characters knowing how Cell storing mechanism works. I have a Character.Cell and Cell.CurrentCharacter properties. In order for setters to work correctly (not go recursively) they should rely on each others implementation. It feels like the model logic should be considered as a single unit.
Make all public members to return interfaces but use exact classes inside (can involve some downcasting). The cons here are such that I should test the whole model as a single and can't use mocking to test different parts independently. Also there is no sense to use dependency injection inside model, only to get another full model implementation from controller.
So what to do?
UPDATE
You can propose other options.
Why are these the only 2 options?
If you intend to have different versions/types of the classes then interfaces/abstract base classes are a good option to enforce shared behaviour and generalize many operations. However the idea of building the classes independently without knowledge of each other is ridiculous.
It is always a good idea to separate class storage/behaviour to the class/layer it belongs. E.g. no business logic code in the data layer, etc. but the classes need to know about each other in order to function properly. If you make everything independent and based on interfaces you run the risk of over generalizing the application and reducing your efficiency.
Basically if you think you would need to ever downcast the incoming objects to more than one type it's a good idea to look at the design and see if you are gaining anything for the performance loss and nasty casting code you are about to write. If you will be required to handle every type of downcast object you have not gained anything and using polymorphism and a base class is a much better way to go.
Using interfaces does not eliminate your trouble in testing. You will still have to instantiate some version of the objects to test most of the functions on the cell/board anyway. Which for full regression testing will require you test each character's interaction with both.
Don't get me wrong, your character class should most likely have a base class or have an interface. All characters will (I'm sure) share many actions and can benefit from this design. E.g. Moving a character on the board is a fairly generic operation and can be made independent of the character except for a few pieces of information (such as how the character moves, if they are allowed to move, etc.) which should be part of said base class/interface.
When it is reasonable, design classes independently so that they can be tested on their own, but do not use testing as a reason to write bad code. Simple stubs or basic testing instances can be created to help with component testing and takes far less time and effort than fixing unnecessarily complex code.
Interfaces have a purpose, but if you will not be treating 2 classes the same... that is not it.
*Using MVC gives you a leg up on testing as well. If done correctly you should be able to swap out any of the layers to ease your testing of a single layer.

What is the best way to arrange this classes? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm doing a simple project to manage data for a tabletop game, but I'm mostly using it to get experience about correct coding.
I've just reached a point where I have five classes that are tightly coupled, and I'm not sure whether leaving the whole thing as it is, or refactoring.
What I have is basically this:
class ShipTemplate: This class ( that has nothing to do with c++ templates ) has all constant members and contains basic informations about a category of Ships.
class TemplateSet: This class contains all ShipTemplates that are currently available to build, and it has a name. It should be stand-alone, since it represents the available technology of each player at any time, so one would be able to save/load different sets at different times.
class Ship: This class represents a complete ship, with loadouts, name and other things. It contains a const reference to a ShipTemplate, which the class is not allowed to change, to refer to its basic functionality. It could extend ShipTemplate, but I wanted to keep track of which Ships had a particular underlying ShipTemplate, and it seemed easier doing it like this.
class Fleet: This class contains a list of Ships, it has a name and contains other information. It should contain a cost variable equal to the sum of the cost of all Ships in it.
class Deployment: This class contains pointers to all the Ships, Fleets, and TemplateSets available to the player. It also needs to keep track of ShipTemplates that are no longer available, but that are still used by already built Ships. It should contain a cost variable equal to the sum of the cost of all Ships available to the Player. It has to manage the transfer of Ships from one Fleet to another. It has to find out which Ships are within a given Fleet, or which Ships have a given ShipTemplate.
Unfortunately every class is pretty interwined with all the others. I thought about different approaches, but I'm not sure if even one of them is the correct one.
Use friend statements all over the place, so that if one class modifies something, it can correctly update all the others.
Use very long names, like Deployment::modifyShipThrustInFleet, and allow any modification solely through the Deployment class, which will take care of everything.
Remove TemplateSets and Fleets and represent them within Deployment, so that it can update correctly cost values/pointers without breaking any "correctness" rule. This too implies that every modification to the system has to pass through Deployment.
Insert into lower classes pointers to upper classes, so for example when changing something in a Ship it can automatically update costs of both its Deployment and Fleet.
Is there some other solution I didn't see, or maybe a refactor into more classes that can help me achieve readable, mantainable code?
Just some thoughts.
When thinking in object oriented way, thinking about real-life objects lays out the view, what you should describe in program. And what is object in real-life? It is a "thing" which has certain features and exposes some functionality.
For example ShipTemplate is a blue-print of the ship. It should define size, layout, part types and quantities (DieselEngine, SteamEngine, AntiAircraftGun, UnderwaterMines, etc), and how they are connected with each other.
Ship on the other had is constructed according to blueprint - it should have all part instances. For example it might have two DieselEngines and three AntiAircraftGuns. And it is correct, that ship does not inherit from blueprint. Blueprint is only a description of ship, not it's parent.
Now, each type of the object (blueprint, part, ship) has it's own properties and functionality. For example, each engine consumes some amount of fuel and can increase speed of the ship to some value. Why not have base class for Engine, which has these features? (inheritance). The same goes for the guns (lets call it ShipWeapon). There is of course a big difference between mine-gun and anti-aircraft gun, but they are both guns, they are both mountable on the ship, they both have weight, ammo type, reload time, ammo capacity, whether gun is operating.
So these are some properties of the objects. What about functionality? Other important concept of OO design is that each object has (encapsulated) some functions which can be done with it (and it may or may not alter objects state). For example ShipWeapon should have method Fire(), which maybe should decrees amount of ammo in it. Or try to target at first with Aim(sometarget). Engine on the other hand would have Start(), Stop(), SetSpeed(speed). Note that these would work internally on the object and it's state. Ship might have SetCourse(direction, speed), which would start it's engines at required power and orient its rudder. Also ship might have Colide(ship). And Hit(typeofattackinggun), which would iterate through all parts of ship and damage some randomly (and set IsOperating for a gun, or turn off one of the engines, etc.)
As you can see you can go into a lot of detail while designing OO approach. Its also very good to know when to stop - just how much detail (or accuracy) you really need for you program to work.
Also, there could be a global World, which would hold all ships. And so on..
There is other part of program, the infrastructure. How you data objects (ships, worlds, players) are managed, how they know and interact with each other. For example each ship as an object can be observed by global map and each ship would notify it about movement (observer pattern). Or global world would query state of each ship at some time intervals, based on global clock. Or...
I guess what I was trying to say is to stick to main OO principles - encapsulation, inheritance, polymorphism. And there is a lot of literature out there for object-oriented design, design patterns, etc., which is useful. Wiki entry is a bit "academic" but has main definitions, which make you think :) Also look at SOLID
PS. And it is usually a sign of a bad design to do everything in a single class.
Now that you have described haw you want to represent the various data, before defining the complete relations, try to complete the description by defining the "protocols":
What can each class be able to do to the others? WHat methods and rules between methods are needed to achieve your goal?
Once you have defined how classes act on each other you will most likely discover what is candidate to be private, what is public and what level of friendship must exist between the parties.
May be is not your case, but -usually- when complex relations exist, one possible pattern can be the use of a "communication bus class", that expose the action that can be "sent" to the various object, each having a private interface and being friend of ... the bus itself (an only the bus).
EDIT
Following Svalorzen comment:
It depends on the side you are watching it.
This will, in fact, introduce multiple level of "privacy", allowing to implement encapsulation on a wider unit that the class itself. Whether this is good or bad is a matter of context, not idiom.
Instead of having just classes with everything private (for no-one else) or public (for anyone), you have a "capsule" that is a "club" (the "club of the classes having 'bus' as a friend") and a "club manager" the is the real "filter towards the public" (and hence the real OOP object), allowing certain methods that need to interact with more classes private parts at a same time, to do that inside the club only.
The deny of "friendship" is nothing more than a misconception that confuse techniques with tools, making OOP objects the same as C++ classes. That's -generally speaking- a FASLE IDIOM. C++ classes can be smaller units than OOP objects (think to the pimpl idiom: what is the "object" there?).
The fact that a class can be a friend of another doesn't make it a friend of anyone, hence the private parts are not made public. You are just defining another level of privacy where encapsulation apply the same as with "private". It just apply on a wider group. That "wider group" plays, respect to OOP, the same role a non-friend class plays.
The misconception that "friend breaks encapsulation" has nothing to do with the concept of OOP. It has to do with the way OOP has been implemented in Java, that is a completely different language respect to C++. In C++ friendsip is just a construct to "group thimgs together" just like class, struct, templates, inheritance, membership etc.
What OOP relation (composition, inheritance, linking...) has to be mapped to what C++ construct, unlike in java, when the language philosophy is defined to be one-way only, is not defined by the language itself and by it's standard library.
The mapping "OOP object = C++ class" is just a common cultural misconception inherited from the past, when C++ has no templates, no lambdas, no friendship, nothing more than classes (and was in fact called "C with classes") when the only way to implement an OOP hierarchy was through classes,since that was the only way to create a hierarchy relation using that time c++ constructs.
Nowadays I can even implement an OOP system using C++ members and implicit conversion for "OOP inheritance" and C++ private inheritance for "OOP membership". Or I can implement an OOP object with a "cluster of classes (or mat be labdas)", defining its run-time behavior (think to std::locale and related facets).
Starting a design with the OOP object == C++ classes idioms is in fact cutting away two degrees of freedom C++ adds to program design, restricting your mind to what C++ was more than ten years ago.

Guarding resources with Singleton?

I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:
Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).
Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).
My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).
Is my choice of making this class a singleton class a bad decision?
Singletons are considered a smell because:
They are the moral equivalent of global variables, and thus their use hides dependencies in code rather than revealing them through interfaces.
They promote tight coupling because your code depends on a specific instance of a specific type. What if you wanted your UI to operate against a different camera manager some day?
They make unit testing difficult because they carry state with them for the entire lifetime of the program. When state is carried across from test to test, it can make tests state-dependent, which is a very big smell.
You can read anything, sooner or later. Regardless of what the
some people say, there's no fundamental reason against using
a singleton in the appropriate cases_. In your case, I have
serious doubts, at least the way you describe it. Regardless of
the API of the camera maker (which is probably in C), your
client code will want to treat each individual camera as
a separate object, and there's nothing inherantly unique about
cameras.
Where a singleton probably is appropriate here is if the API of
the camera maker is in C, and you decide to provide
a lightweight C++ wrapper for it, to be used (exclusively) by
your Camera classes. Such light weight wrappers are one
legitimate use of singletons---there's no way in the world you
can have several instances of the library in your code.
(Usually, however, it's easier to have the Camera class address
the API directly, and skip the intermediate wrapper.)
Is my choice of making this class a singleton class a bad decision?
Yes.
Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).
That doesn't make it necessary to access the camera via a Singleton class.
Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).
Using a Singleton class will not buy you anything that saves you from those problem that you cannot also do in a non-Singleton class.
My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).
Then there's no need to create a God-like Singleton class.
Furthermore, those little nifty helper functionalities you added to the Singleton class and their interactions with other pieces of code cannot easily be unit tested when residing in a singleton class with global state that cannot properly be set up and torn down between tests.
By proper use of dependency injection in the application composition root, the concrete object lifetime can be managed as if it was a singleton, but the individual clients of that object doesn't need to know that.
I personally think it is reasonable to use Singletons when appropriate. There certainly may be overuse of them in general, but in my opinion they are useful for manager classes controlling hardware resources, which is what you are doing.
Yes and No
No because the problems you see about concurrency are problems you can't "safely" avoid while playing with threads. Sooner or later, bad synchronization mechanisms will come back at you and break your lovely code. You WILL need mutexes and semaphores and such to guard ressources.
Yes, because the singleton is a bad pattern to involve with threads. Check this page about singletons, you will see some pitfalls associated with it. Basically, you're asking for trouble.
Regarding the general "Singletons are evil", it is because it makes it much harder to figure out how it works, they are the OOP version of global variables. Suppose that you have a singleton somewhere, that gets modified in 15 places, how do you track it all? If you had a "real" object, you'd be able to see how it is passed around in parameters and such. The singleton breaks the concept of scope and is easy to transform into a mess.
Singleton and Monostate patterns are both useful in this regard. Your primary consideration (regarding your second point) is to prevent multiple accesses, and neither Singleton nor Monostate prevent this.
Yes, making it a Singleton is a bad design. If you only need one Camera object, just make one.
If you need to ensure that a camera object is used in a non-reentrant way, than that is a responsibility not of the Camera object, but of your threading model. It's a seperate job.

Register Game Object Components in Game Subsystems? (Component-based Game Object design)

I'm creating a component-based game object system. Some tips:
GameObject is simply a list of Components.
There are GameSubsystems. For example, rendering, physics etc. Each GameSubsystem contains pointers to some of Components. GameSubsystem is a very powerful and flexible abstraction: it represents any slice (or aspect) of the game world.
There is a need in a mechanism of registering Components in GameSubsystems (when GameObject is created and composed). There are 4 approaches:
1: Chain of responsibility pattern. Every Component is offered to every GameSubsystem. GameSubsystem makes a decision which Components to register (and how to organize them). For example, GameSubsystemRender can register Renderable Components.
pro. Components know nothing about how they are used. Low coupling. A. We can add new GameSubsystem. For example, let's add GameSubsystemTitles that registers all ComponentTitle and guarantees that every title is unique and provides interface to quering objects by title. Of course, ComponentTitle should not be rewrited or inherited in this case. B. We can reorganize existing GameSubsystems. For example, GameSubsystemAudio, GameSubsystemRender, GameSubsystemParticleEmmiter can be merged into GameSubsystemSpatial (to place all audio, emmiter, render Components in the same hierarchy and use parent-relative transforms).
con. Every-to-every check. Very innefficient.
con. Subsystems know about Components.
2: Each Subsystem searches for Components of specific types.
pro. Better performance than in Approach 1.
con. Subsystems still know about Components.
3: Component registers itself in GameSubsystem(s). We know at compile-time that there is a GameSubsystemRenderer, so let's ComponentImageRender will call something like GameSubsystemRenderer::register(ComponentRenderBase*).
Observer pattern. Component subscribes to "update" event (sent by GameSubsystem(s)).
pro. Performance. No unnecessary checks as in Approach 1 and Approach 2.
con. Components are badly coupled with GameSubsystems.
4: Mediator pattern. GameState (that contains GameSubsystems) can implement registerComponent(Component*).
pro. Components and GameSubystems know nothing about each other.
con. In C++ it would look like ugly and slow typeid-switch.
Questions:
Which approach is better and mostly used in component-based design? What Practice says? Any suggestions about (data-driven) implementation of Approach 4?
Thank you.
Vote for the third approach.
I am currently working on component-based game object system and i clearly see some of additional advantages of this approach:
The Component is more and more self-sufficing subentity as it depends only on a set of available subsystems (i presume this set is fixed in your project).
Data-driven design is more applicable. Ideally, this way you may design a system where components are completely defined in the terms of data but not C++.
EDIT: One feature i thought about while working on CBGOS. Sometimes it is convenient to have ability to design and construct subsystemless passive components. When this is on your mind the fourth approach is the only way.
My approach was to implement the proxy pattern within each subsystem. As each subsystem is only interested in a subset of the total components each entity may contain, The proxy stores pointers to only the components the system cares about, eg, a motion system only cares about position and velocity, so it needs a proxy which stores two pointers, to those components. If the entity is missing one or more of those, then the subsystem will ignore it. If both components are present, then a proxy node is created and added to an internal collection. It is also useful for the proxy to store the unique identifier value for the entity, so that proxies may be added/removed in constant time from each subsystem, should it be necessary.
In such a way, should an entity be required to be removed from the engine, a single message containing the id of the entity can be sent to every subsystem. The proxy can then be removed from each subsystem collection independently.

Mixing component based design and the model-view(-controller) pattern

'm developing a 2D game and I want separate the game engine from the graphics.
I decided to use the model-view pattern in the following way: the game engine owns game's entities (EnemyModel, BulletModel, ExplosionModel) which implement interfaces (Enemy, Bullet, Explosion).
The View receives events when entities are created, getting the pointer to the interface: in this way the View can only use the interface methods (i.e. ask for informations to perform the drawing) and cannot change the object state. The View has its onw classes (EnemyView, BulletView, ExplosionView) which own pointers to the interfaces.
(There is also an event-base pattern involved so that the Model can notify the View about entity changes, since a pure query approach is impraticable but I wont' discuss it here).
*Model classes use a compile-time component approach: they use the boost::fusion library to store different state componets, like PositionComponent, HealthComponent and so on.
At present moment the View isn't aware of the component based design but only of the model-view part: to get the position of an enemy it calls the Enemy::get_xy() method. The EnemyModel, which implements the interface, forwards this call to the PositionComponent and returns the result.
Since the bullet has position too, I have to add the get_xy method to Bullet too. BulletModel uses then the same implementation as the EnemyModel class (i.e. it forwards the call).
This approch then leads to have a lot of duplicate code: interfaces have a lot of similar methods and *Model classes are full of forward-methods.
So I have basically two options:
1) Expose the compoment based design so that each component has an interface as well: the View can use this interface to directly query the component. It keeps the View and the Model separated, only at a component level instead of a entity level.
2) Abandon the model-view part and go for pure component based design: the View is just a component (the RenderableComponent part) which has basically full access to the game engine.
Based on your experience which approach would be best?
I'll give my two cents worth. From the problem you're describing, it seems to me that you need an abstract class that will do the operations that are common amongst all of your classes (like the get_xy, which should apply to bullet, enemy, explosion, etc.). This class is a game entity that does the basic grunt work. Inheriting classes can override it if they want.
This abstract class should be the core of all your interfaces (luckily you're in C++ where there is no physical difference between a class, and abstract class and an interface). Thus the Views will know about the specific interfaces, and still have the generic entity methods.
A rule of thumb I have for design - if more than one class has the same data members or methods, it should probably be a single class from which they inherit.
Anyway, exposing the internal structure of your Model classes is not a good idea. Say you'll want to replace boost with something else? You'd have to re-write the entire program, not just the relevant parts.
MVC isn't easy for games as when the game becomes larger (including menu, enemies, levels, GUI...) and transitions, it'll break.
Component or entity-system are pretty good for games.
As a simpler case for you, you may consider using a HMVC. You'll still have issues with transitions, but at least your code will be grouped together in a more clean manner. You probably want your tank's code (rendering and logic) to get close together.
There have been presentation architectures designed especially for agent-based systems, such as Presentation-Abstraction-Control. The hard part in designing such a system is that you ultimately end up hardwiring sequences of collaborations between the agents.
You can do this, but don't use OO inheritance to model the message passing hierarchy. You will regret it. If you think about it, you are really not interested in using the OO inheritance relationship, since the interfaces defined are really just a "Record of functions" that the object can respond to. In that case, you are better off formally modeling your communication protocol.
If you have questions, please ask -- this is not an obvious solution and easy to get wrong.