Sign in to follow this  

Namespaces in classes

This topic is 4526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This doesn't seem to be possible. But wouldn't it help a lot? I wish I could derive a world-like object from an engine-like class to recieve some functionality from it, but it would be nice to keep it's engine-level routines seperate from the object's worldly routines. Here's an example:
class ParticlePhysics
{
public:
   namespace Particle
   {
      void UpdatePhysics();
      void UpdateFade();
      void DieOut();
      void StartFloating();
   };
private:
.....
};

class MadMan : public ParticlePhysics
{
public:
   void Update()
   {
      Particle::UpdatePhysics();
   }
private:
...
};
Compare to something like this:
class ParticlePhysics
{
public:
   void Particle_UpdatePhysics();
   void Particle_UpdateFade();
   void Particle_DieOut();
   void Particle_StartFloating();

private:
.....
};

class MadMan : public ParticlePhysics
{
public:
   void Update()
   {
      Particle_UpdatePhysics();
   }
private:
...
};
This is a really bad example. I have no idea why MadMan would want to be derived from a particle. But I find myself having this problem sometimes. Some classes are made to be derived from for this purpose. And I wish there was some way to prevent confusion. Is there another way? Thanks for any suggestions

Share this post


Link to post
Share on other sites
It's a bad idea. Basic rule of thumb: a class should do only one thing.

Besides, in your example, the namespace doesn't do anything except add redundant scope. Just do this instead:
    class MadMan : public ParticlePhysics
{
public:
void Update()
{
ParticlePhysics::UpdatePhysics();
}
};

Share this post


Link to post
Share on other sites
Quote:
Original post by JohnBolton
It's a bad idea. Basic rule of thumb: a class should do only one thing.

It's not an idea, I just want to make things easier to organize and follow. I'm not sure I understand the relevance of your basic rule of thumb statement.

Quote:
Besides, in your example, the namespace doesn't do anything except add redundant scope.

Isn't that what all namespaces do? That's what I wanted it to do. Same reasons.

Quote:
Just do this instead

That's pretty obvious, but it's more than just about calling the function name.

Thanks for your time

Share this post


Link to post
Share on other sites
Quote:
Original post by Jiia
Quote:
Original post by JohnBolton
It's a bad idea. Basic rule of thumb: a class should do only one thing.

It's not an idea, I just want to make things easier to organize and follow. I'm not sure I understand the relevance of your basic rule of thumb statement.


He's critisizing the fact that your design makes you feel the need for such prefixes.

Quote:
Quote:
Besides, in your example, the namespace doesn't do anything except add redundant scope.

Isn't that what all namespaces do?


No, namespaces add scope/organization so things dont clash. This repeatedly, reiteratingly (that a word?) and redundantly adds scope/organization:

You can use the ClassName:: prefix to access that scope to prevent clashes
just like:
You can use the NamespaceName:: prefix to access that scope to prevent clashes
outside of a class.

There's no need to wrap all the members of ParticlePhysics in a namespace scope, because they're allready in a class scope.

Quote:
This is a really bad example... But I find myself having this problem sometimes.


Why create a bad example when you allready have examples (your previous experiences)?

Share this post


Link to post
Share on other sites
Quote:
Original post by MaulingMonkey
He's critisizing the fact that your design makes you feel the need for such prefixes.

Criticizing was not the help I was looking for, but I still don't see the relevance, or why we're thinking that bad design is lurking.

Quote:
There's no need to wrap all the members of ParticlePhysics in a namespace scope, because they're allready in a class scope.

...

Why create a bad example when you allready have examples (your previous experiences)?

The method is exactly the same; I'm deriving from a class. The inherited class is very complex, and the base class is very simple. I use the IDE's tools to access and write code, and that means a lot of functions exist for this class that are all thrown together. Compiler auto-completion alone is enough reason to use prefixes. There are about five functions that deal with collision. It would be nice to provide a Collision:: prefix for them in the class. There are at least 15 that work with animations, 6 that update commands, 8 that update command tasks, 13 that handle equipment and armor, five or so that just divide normal updating code, around 12 for AI routines, and 3 for input.

When I type Character->, I get a table of contents. It's great, I would just like to organize it.

Share this post


Link to post
Share on other sites
Quote:
Original post by Jiia
I'm not sure I understand the relevance of your basic rule of thumb statement.

I assume by wanting namespaces inside a class, you want to do something like this:
    class A
{
namespace X
{
...
}
namespace Y
{
...
}
namespace Z
{
...
}
};
This implies to me that the class has three separate behaviors or modes of functionality. Better would be to divide A into three separate classes, or make X, Y, and Z classes rather than namespaces.

Share this post


Link to post
Share on other sites
Quote:
Original post by JohnBolton
This implies to me that the class has three separate behaviors or modes of functionality. Better would be to divide A into three separate classes, or make X, Y, and Z classes rather than namespaces.

All three behaviors are exclusive to A. Wouldn't adding a new class for every routine that requires more than one function make a mess of things? The routines deal directly with the object. They are part of the object. I would have to pass this pointers to each class function just to have it function properly. Then there's the matter of private data, which the routines obviously need. I would end up making my whole project a huge library of one-use classes. That doesn't sound like the answer I'm looking for.

Share this post


Link to post
Share on other sites
without a specific example of when this usage pattern would be
required/prefered, it may be hard for others to see why one would
want to use it. if you have a pre-existing example, sharing it
might help others see what you mean.

in your example, it seems like your Particle Physics class is managing
particle physics and particle persistence as well some display
functionality (though i may be misinterpreting what fade out is doing).
that would be 2 maybe 3 seperate seperate processes stuffed into one
class. and then the class being derived by 'Madman' helps little in
explaining how this usage pattern could be helpful.

illone

Share this post


Link to post
Share on other sites
I have a large, complex class that is very flexible and does many different things. I want to organize all of the routines it can perform.

I'll find my own way. I appreciate the help.

Share this post


Link to post
Share on other sites
Instead of namespaces inside of a class, what about classes inside of a namespace?
namespace ParticlePhysics
{
class Particle
{
public:
void UpdatePhysics();
void UpdateFade();
void DieOut();
void StartFloating();
};
}

Share this post


Link to post
Share on other sites
Quote:
I have a large, complex class that is very flexible and does many different things.

There's a word for that in Object Oriented Programming: It's called Low Cohesion, and it's a sign of a bad design. I know you didn't create this thread to get critical feedback on your design, but you should really look into this, and why it can be a bad thing.

Share this post


Link to post
Share on other sites
The primary intent of namespaces is to provide a mechanism for partioning class, struct, function, and other definitions to eliminate naming conflicts. Examples would be classes contained in the STL. Without namespaces you may end up with conflicts classes such as list, string, and exception. The syntax and more importantly how the compiler handles namespaces isn't very applicable inside of a class declaration. If parts of the language were changed to support this type of declarations the amount of resulting ambiguity in the use of namespaces would in all likelyhood degrade it's usefulness.

From what I can tell the only real reason you are wanting to do this is because of the auto completion feature in the IDE you are using (no it's NOT part of the 'compiler'). This is really the wrong reason for even considering doing such a thing. The suggestions and/or criticism concerning how your classes are design should be considered as constructive and good advice - especially since they are coming from a large group of VERY experienced individuals. Considering that you are working with a very large class that includes a wide set of complex operations you really should consider breaking it down into multiple classes containing sets of specific operations.

Share this post


Link to post
Share on other sites
Perhaps the reason it's considered bad design is lack of organizing code tools? I have no problem with critical feedback, but the only advice I've seen so far was to use classes to seperate tasks that my object can perform. That does provide the grouping of that single routine type, but at a messy cost. In the end, I have twenty really tiny classes that are exclusive in their use to characters and share tons of data with each other. I fail to see how this is an improvement.

Sure, I can build a class that controls the character's eyes to look around, and a class to enable or disable control systems, and a class to handle path node updates. Also a class for moving equipment into and out of hands, inventory and the invironment. Another class to handle equipping suits, checking suit compatibility, updating suit dependencies, and updating their effect on the character (note that I already have a suit class, but now I'll have a CharacterSuitManagement class). Then my characters have something called "action events". These are ways that characters can interact with the world. For example, they could walk into an area trigger and an action event is presented to them for them to make a choice. There are three functions dealing with and managing action events. I already have an ActionEvent type class, but now I'll have CharacterActionEventManagement class. You might say that a three function routine isn't enough of a reason to want change, but you soon change your mind when there are 20 routines that all have three functions. There are several routines for standing, about five for moving, three or four for climbing on ledges, only two for aiming ranged weapons, and a few for updating directions - movement, facing, and looking are all seperate states that are updated individually.

Almost every task in this class can be grouped by it's purpose, but it doesn't fit into another class. It doesn't make sense as one. If I'm mistaken, please enlighten me.

Share this post


Link to post
Share on other sites
Quote:
Original post by Helter Skelter
From what I can tell the only real reason you are wanting to do this is because of the auto completion feature in the IDE you are using (no it's NOT part of the 'compiler').

Forgive my IDE/Compiler wording mixup, that was very inexcusable of me.

Share this post


Link to post
Share on other sites
Quote:
Original post by Jiia
Perhaps the reason it's considered bad design is lack of organizing code tools?


That's like blaming a word processor for bad grammar. Design has nothing to do with languages, tools, or even specific compilers. Even low level designs have an abstraction above their actual implementation.

Quote:
I have no problem with critical feedback, but the only advice I've seen so far was to use classes to seperate tasks that my object can perform.


You've only provided a minimal amount of information. In deciding which functionality should be moved to a different class you really have to decided where that functionality really belongs. Take a file parser for instance. I may create a class that reads from a file, turns each symbol into a token, and then acts on specific sequences of tokens. If I ever want to change that class to parse text that is already loaded in memory I either replace the file reader OR include additional code to handle in-memory specific parsing.

Alternatively I can take each group of functionality and place them in separate classes to make it more extensible. In doing this I may create a stream class (called FileStream) to handle input, a single class that reads from the stream and converts the input into tokens (called Tokenizer), and a class which acts on token stream do to specific operations (called Parser). Now if I want to add support to parse information already in memory I create a new stream type class (called MemoryStream) which gets passed to the tokenizer. In short I can add, replace, or change existing components without breaking the others or having to modify them to support the changes.

You just need to look at your overall design, separate functionality into logical blocks, then decide whether inheritence or composition is more applicable to how everything works together.


Quote:
Almost every task in this class can be grouped by it's purpose, but it doesn't fit into another class. It doesn't make sense as one. If I'm mistaken, please enlighten me.


Maybe it does maybe it doesn't. That's the entire reason posters have suggested you revisit your design and decide if chances are necessary. Design is not simple nor is every design decision obvious. I'm sure that if you posted specific examples (i.e. your class definitions) with sufficient information about dependencies, use, and relationship others on the forum will be more than happy to make suggestions and possibly even provide a step by step blow of why they make certain decisions.

Share this post


Link to post
Share on other sites
Quote:
Original post by Helter Skelter
Quote:
Original post by Jiia
Perhaps the reason it's considered bad design is lack of organizing code tools?

That's like blaming a word processor for bad grammar.

It's more like blaming the height restriction of my skyscraper on the building materials. (edit: By code-tools, I was referring to tools in code, not tools to work with code. IE, language features)

Quote:
You've only provided a minimal amount of information.

How much information do you need? There's a lot of functions in a class, and that gets confusing. How difficult is that to follow? If there were a way to group functions by purpose, it would be much more manageable. Or at least I would think so.

Quote:
In deciding which functionality should be moved to a different class you really have to decided where that functionality really belongs.

It belongs where it's at. That's why I put it there. I have no grudge against writing new classes, but it makes no sense in most of these situations.

Quote:
Alternatively I can take each group of functionality and place them in separate classes to make it more extensible. In doing this I may create a stream class (called FileStream) to handle input, a single class that reads from the stream and converts the input into tokens (called Tokenizer), and a class which acts on token stream do to specific operations (called Parser).

Let's look at it from another angle. Lets say your parser includes several string management functions. Just three or four to compare, convert, search, or whatever. Then say it has a few error checking routines to see if things are going bad with the stream. Multiply this type of growth by twenty, and you have what I have. And it's still growing rapidly. You're telling me to create a class to search, manage, and convert parser strings from it's stream, even though the class will contain no data and only has three functions. The stream would also need sent to the class for each function.

Quote:
Design is not simple nor is every design decision obvious. I'm sure that if you posted specific examples (i.e. your class definitions) with sufficient information about dependencies, use, and relationship others on the forum will be more than happy to make suggestions and possibly even provide a step by step blow of why they make certain decisions.

I don't have time to edit the source enough to be decent for posting. My IDE font is very small, so my comments run really far to the right. That means the source box will explode and you'll have a 5000 pixel wide thread page. It really is a huge class, hence the reason I'm looking to improve it's managment. The class declaration itself is about 200 lines of code.

Like I said, I appreciate the help. I'll find my own way around it.

Share this post


Link to post
Share on other sites
Quote:

How much information do you need? There's a lot of functions in a class, and that gets confusing. How difficult is that to follow? If there were a way to group functions by purpose, it would be much more manageable. Or at least I would think so.


The people in this thread have been trying to tell you that your design is at fault here, not the language.

It turns out that there is a construct for grouping functions by purpose that is very managable in this scenario - they're called classes.


Quote:

I have a large, complex class that is very flexible and does many different things.


You created a large class with multiple responsibilities. Why don't you move the functionality of this class into several other classes and use your ParticlePhysics class as a facade (that's basically an interface class)?

Share this post


Link to post
Share on other sites
Sorry if I'm being dumb (I don't use inner structs very often), but can't you use inner structs instead of namespaces to do what you want? I know there are some (compiler related) problems when determining scope rules for inner structs (e.g. in the following example some compilers won't let ParticlePhysics::Particle::UpdatePhysics() access or modify a ParticlePhysics::m_doo). Try it out and see what you get:


class ParticlePhysics
{
public:
// ...

protected:

struct Particle
{
// doesn't modify state
static void UpdatePhysics();

// ...
};

struct Whatever
{
// modifies state
void Bar();

// ...

private:
int m_choo;

} whatever; // note: Whatever has state - requires instance

private:
int m_doo;
};

class MadBugger : public ParticlePhysics
{
public:

void Update()
{
// static method
Particle::UpdatePhysics();

// ...

// instance method
whatever.Bar();
}

};




Sometimes better code readability and usability require 'unpopular' methods to get the job done; remember that everyone here is only trying to help (in a very general way), albeit without the wider understanding of the scope, overall design, or implications of what you have presented here. Good luck! [smile]

Edit: improved example to show inner struct semantics with and without state, and need to have instance of ParticlePhysics::Whatever; also made inner structs protected

[Edited by - ajones on July 21, 2005 3:40:42 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Jiia
By code-tools, I was referring to tools in code, not tools to work with code. IE, language features.

Regardless, programming languages have nothing to do with bad design.
Quote:
If there were a way to group functions by purpose, it would be much more manageable. Or at least I would think so.

Ummmm...that's what classes are for.
Quote:
Let's look at it from another angle. Lets say your parser includes several string management functions. Just three or four to compare, convert, search, or whatever.

that depends. If the string functions can be considered general purpose they will most likely end up in a utility class, string class, or in their own little section of the program. Support for strings is broad enough that they in all likelyhook belong elsewhere.
Quote:
Then say it has a few error checking routines to see if things are going bad with the stream.

That functionality belongs in the appropriate stream class. All the parser cares about is if data is available or the end of input has been encountered.
Quote:
Like I said, I appreciate the help. I'll find my own way around it.

Good luck.

Share this post


Link to post
Share on other sites
Quote:
Original post by ajones
Sorry if I'm being dumb (I don't use inner structs very often), but can't you use inner structs instead of namespaces to do what you want?


/*
* I believe he wants to do something like this:
*/

class foo {
int member_variable;
namespace bar {
void function() {
member_variable = 3;
}
}
};
/*
* You cannot directly emulate this in C++:
*/

class foo {
int member_variable;
class bar {
void function() {
/*
* error: foo::bar is instantiatable completely independantly from a
* foo object - which foo's member_variable do we use?
*/

member_variable = 3;
}
};
};
/*
* You can work around this by mantaining a reference manually... something
* similar to this is an option:
*/

class foo {
int member_variable;
class bar_impl {
foo & parent;
bar_impl ( foo & parent ) : parent( parent ) {}
void function() {
parent.member_variable = 3;
}
} bar;
foo () : bar( *this ) {}
};

/* There is some added overhead (one reference per type/subgroup) using this
* method. Considering the only good argument for class sub-namespaces seems to
* be related to intellesense, I might recommend using non-member functions in
* conjunction:
*/


class pie {
public:
void foo_eat( void ) {}
void foo_make( int arg ) {}
void foo_throw_it( void ) {}
void bar_eat( void ) {}
void bar_make( int arg ) {}
void bar_throw_it( void ) {}
};

namespace foo {
void eat( pie & self ) { self.foo_eat(); }
void make( pie & self , int arg ) { self.foo_make( arg ); }
void throw_it( pie & self ) { self.foo_throw_it(); }
}

namespace bar {
void eat( pie & self ) { self.bar_eat(); }
void make( pie & self , int arg ) { self.bar_make( arg ); }
void throw_it( pie & self ) { self.bar_throw_it(); }
}

pie my_pie;

//equivilant lines:
my_pie.foo_eat();
foo::eat(my_pie);

//equivilant lines:
my_pie.bar_make(3);
bar::make(my_pie,3);

...


Share this post


Link to post
Share on other sites
Quote:
Original post by MaulingMonkey
I believe he wants to do something like this:

/* assignment to outer class member variable from inside inner class*/

You cannot directly emulate this in C++


If so, there's a directly related discussion in the C++ Users Journal (you can also find the article here) that provides examples of how to work around the problem (although they're ugly); it also references a standard revision that should solve this language defect (access rules for nested classes).

Note that this is only relevant if Jiia does intend to mutate an outer member variable from an inner class; as long as Jiia only requires access from outer to inner scope (i.e. MadMan uses Particle:: members, but Particle:: doesn't make use of ParticlePhysics:: members), then an inner class is fine.

Share this post


Link to post
Share on other sites
Quote:
Original post by MaulingMonkey
Quote:
Original post by ajones
Sorry if I'm being dumb (I don't use inner structs very often), but can't you use inner structs instead of namespaces to do what you want?


*** Source Snippet Removed ***



Actually when this thread was started I checking by doing something like that. About the closest I came to was creating an inner class that contained a reference to the outer class and overloaded the -> operator in the inner class to return a pointer to the outer class.
class Outer {

void DoSomething();

class Inner {
public:
Outer &outer;
Outer *operator->() {
return &outer;
}
};
public:
Inner Particle;
};

Outer outer;
outer.Particle->DoSomething();


In the end it's ugly and pointless.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Helter Skelter
In the end it's ugly and pointless.


From my current (PhD) project's resource system (apologies for the huge source snippet - I just want to present a complete example):


class CfgElement
{
public:
explicit CfgElement(ASSET_SYSTEM::AssetDataIterator& in,
RESOURCE_SYSTEM::qualified_elements& qualifiedElements,
RESOURCE_SYSTEM::qualified_attributes& qualifiedAttributes,
const std::string& parentQualifiedName);

inline const std::string getName() const
{ return m_name;
}
inline const std::string getQualifiedName() const
{ return m_qualifiedName;
}
public:

struct elements_collection
{
public:
typedef CFG_ELEMENTS::named_elements named_elements;
typedef CFG_ELEMENTS::named_iterator named_iterator;
typedef CFG_ELEMENTS::named_range named_range;

typedef CFG_ELEMENTS::ordered_elements ordered_elements;
typedef CFG_ELEMENTS::ordered_iterator ordered_iterator;
typedef CFG_ELEMENTS::ordered_range ordered_range;
public:
const named_range get(const std::string& name) const;
const named_iterator begin_named() const;
const named_iterator end_named() const;

const ordered_iterator get(const size_t& index) const;
const ordered_iterator begin_ordered() const;
const ordered_iterator end_ordered() const;
private:
friend class CfgElement;
elements_collection();
named_elements m_named;
ordered_elements m_ordered;
}elements;

struct attributes_collection
{
public:
typedef CFG_ATTRIBUTES::named_attributes named_attributes;
typedef CFG_ATTRIBUTES::named_iterator named_iterator;
typedef CFG_ATTRIBUTES::named_range named_range;

typedef CFG_ATTRIBUTES::ordered_attributes ordered_attributes;
typedef CFG_ATTRIBUTES::ordered_iterator ordered_iterator;
typedef CFG_ATTRIBUTES::ordered_range ordered_range;
public:
const named_iterator get(const std::string& name) const;
const named_iterator begin_named() const;
const named_iterator end_named() const;

const ordered_iterator get(const size_t& index) const;
const ordered_iterator begin_ordered() const;
const ordered_iterator end_ordered() const;
private:
friend class CfgElement;
attributes_collection();
named_attributes m_named;
ordered_attributes m_ordered;
}attributes;

private:
std::string m_name;
std::string m_qualifiedName;
};



I still maintain that inner structs are a valid solution to the OP's problem - the above code compiles fine under VC++ .NET 2003, where the body of CfgElement's constructor is actually responsible for inserting both elements and attributes into the respective collections' containers. Neither element_collection not attribute_collection make any use of the outer (CfgElement) class. CfgElement's interface, given its context and suitable documentation, is clean and easily understood, despite the use of two nested structs to group semantics.

I'm sorry if I'm being a bit anal about this [razz] - I just see it as a potential solution to the OP's problem; the use of inner structs can be ugly if you need inner -> outer access (I'm certainly not arguing that point), but the OP has yet to confirm this.

Share this post


Link to post
Share on other sites

This topic is 4526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this