Hi!
I have a working prototype of a game engine and right now I’m doing some refactoring.
What I’m asking for is your opinion on usage of the following C++ coding patterns.
I have implemented some trivial algorithms for collision detection and they are implemented the following way:
Not shown here – class constructor is made private and using algorithms looks like Algorithm::HandleInnerCollision(...)
class Algorithm {
// Private routines
static bool is_inside(Point& p, Object& object) {
// (...)
}
public:
/**
* Handle collision where the moving object should be always
* located inside the static object
*
* @param MovingObject & mobject
* @param const StaticObject & sobject
* @return void
* @see
*/
static void HandleInnerCollision(MovingObject& mobject, const StaticObject& sobject) {
// (...)
}
So, my question is – somebody advised me to do it “the C++” way – so that all functions are wrapped in a namespace, but not in a class. Is there some good way to preserve privating if I will wrap them into a namespace as adviced?
What I want to have is a simple interface and ability to call functions as Algorithm::HandleInnerCollision(...) while not polluting the namespace with other functions such as is_inside(...)
Of, if you can advise any alternative design pattern for such kind of logics, I would really appreciate that…
If the various functions have something to do with each other, if it’s more than helping but really have a common factor such as acting on the same entity, then put them in a class. On the other hand, if a function acts on the same entity as others, but you also want to reuse it for other entities that are convertible to the first entity then extract it outside of the class:
The above function will work with any two objects that are convertible to or descend from
shape.Put functionality that you don’t want to share with other translation units (i.e. helper functions and help objects) in an unnamed namespace. This is the C++ equivalent of the C static functions, and it instructs the compiler to keep anything inside the unnamed namespace private to this translation unit.
Put all the functionality that you want to share with other translation units in a named namespace. This will instruct the compiler to wrap the code with a common name, so names don’t collide with external code (libraries etc.) names.