Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a C++ program that has a large number of classes. In my head I can visualise them as distinct collections. For example there's a collection of classes for reading and storing config data, and another collection for drawing a user interface with various widgets.
Each of those collections could be neatly stored inside separate namespaces, which seems sensible. The config part has a "screen" class, and the GUI part also has a "screen" class, but they are different to each other. I could rename one "gui_screen" and the other "config_screen", but that's the point of a namespace isn't it? To remove these prefixes we invent to separate things.
Part of me then thinks it'd be tidy to store those namespaces inside one main one so that none of my code can interfere with the namespaces of anything else. And I suppose it might also make the code more readable too.
Or am I just making overly complex hierarchies of data for no reason at all?
If you're having namespaces with common names such as "gui" and "config", and it's possible that your code may in the future be part of a library meant to be linked with other code not under your control, it might indeed be a good idea to nest all of "your" namespaces into a single named one (which probably should have no other content except the nested namespaces) which identifies them as "yours". There is really no penalty for doing so, especially if, as you think, it can be done in a way that helps readability. (That's quite different from deep nested hierarchies of class inheritance, which can definitely hamper clarity, as different functionality is added at each layer and a reader or maintainer of the code has to be jumping around among many files to see or change what's added where!-)
No, IMO you're not overdoing at all.
And resist the temptation to use using declarations or (heaven forbid!) using directives! It takes very little getting used to always typing all namespaces and, once you're used to it, it makes the code much easier to read and understand. ("Which screen type is this again, gui or config?")
Personally I've never seen more than two levels of namespace nesting that was at all meaningful or useful. What you've described sounds fine, but I wouldn't go any deeper than project::component unless you've got a tangible, demonstrable, "this breaks without it" reason to do so. In other words, foo::bar::screen is reasonable, foo::bar::ui::screen is highly questionable, and anything more than that almost certainly introduces more complexity than is justified.
It is not overkill. It is reasonable to nest your namespaces, e.g. piku::gui::screen etc.
You could also collapse them to piku_gui_screen, but with the separate, nested namespaces you get the advantage that, if you're inside piku::gui, you can access all names in that namespace easily (e.g. screen will automatically resolve to piku::gui::screen).
Defining namespaces you are not doing any hierarchy, so I don't see what the problem is, anyway namespace are there just to solve your very problem.
I personally love to group files/classes by their functionality. I normally start with a folder with a name that matches the namespace I will use. Eventually if a namespace needs to be reused in another application, you can easily take it out and build it into it's own dll and share it.
It also makes for nice intellisense so that when I'm drilling down through namespaces, I can see just the classes that are part of that group of functionality.
It seems to me that one namespace per developer ought to be enough -- you (presumably) have control over all the type names you define in your own code, and it's unlikely that you'll want to use the same type name for different types within the same project.
I think the main use of namespaces is to handle the case where two independent developers happened to choose the same type name -- without namespaces you'd have no way to use both developers' code in the same project. Multiple namespaces within a single developer's codebase, OTOH, just add complexity and typing overhead, with little or no compensating benefit.
All IMHO, of course.
Related
This is confusing me a great deal. All code examples being namespaceA and namespaceB and the method names being foo() and bar() are not helping, either. The way everyone explains it makes it seem as though namespaces are a relic of pre-OOP times where you could not say 'class car give fuel level' but had to go to this from another approach. But when I now want to do a C++ level, what is the point of using namespaces? Not that headers are confusing enough already, namespaces make absolutely no sense to me, in either how they work or why to use them.
Let's say I have a project built around Traffic, for example. You'd have classes for the Cars and its components, the Drivers and Passengers and the Road.
Now, the Road has Cars and each Car has Persons. What would this look like?
Would you have the namespaces Road, Car, Person? Would the main() use the namespace Road to access the stuff in the header? Would the namespace Road include the namespace Car, and the Car include the namespace Person, and would through this the main() have access to the methods in Person? This is the way most guides explain this, but I don't really see the advantage of this over just importing the header file, wouldn't that have the same effect?
Or would you put multiple headers in the same namespace, such as namespace Traffic with all those classes? Can you nest namespaces?
I know C# and never knew it had namespaces until I looked it up just now, and never needed it, and in Java, Python, and Dart, those also never came up. Since I am trying to teach myself C++, I am kind of stranded here now, asking this question here. So far, I also never used them in C++, but I want to learn it properly.
For small, self-contained projects, there's not much need for namespaces, and you'd never create a namespace for each object or concept in your code.
Larger projects using libraries benefit from being isolated from names introduced by those libraries, as well as some internal organisation to make readability easier.
Similarly, when creating a library, it's a good idea to put its contents into a namespace so as not to cause headaches and conflicts for your users (as you don't know how large their projects will be, and what names they may want to use themselves).
To use an analogy: if you have three books, you don't bother organising them alphabetically. But, once you have a hundred, you might decide to categorise them on your bookshelf for easier reference and mental health.
And, if you now borrow another twenty books from a friend, you'd probably keep those in a separate pile so they're easier to find when you need to give them back.
So, to some degree, this is a case of… you'll know why you need it, when you need it.
If I make a library with a function calculateStuff() in it and you also make a library with a calculateStuff() function, then some other person who wants to use both our libraries at the same time is going to have a bad day. But, if we both used namespaces there's no problem since he/she can then distinguish the functions as myNamespace::calculateStuff() and yourNamespace::calculateStuff() and there's no ambiguity.
For example: std::shared_ptr vs boost::shared_ptr. Without namespaces you wouldn't be able to use both in the same program as the name shared_ptr would be ambiguous.
"[Named] Namespaces" are, as the name perhaps suggests, a way to subdivide the identifier space. In addition to solving literal conflicts ("you have more than one foo ..."), it also makes it considerably easier to find foo in a big, mature program that might well consist of hundreds or even thousands of modules.
The "name" of a variable or routine might(?) suggest what it is, but might not give any clue as to where it is, nor the context (not a technical term) of what it relates to: "it's just one name among many thousands." But, if you now group these into intelligently-chosen namespaces, you're adding a level of helpful organization to them. In a typical "great big program," especially one that is (as is also typical ...) "not entirely familiar to you," this extra level of bread-crumbs is a big bonus.
Simply put, namespaces allow to use the same names for different contexts.
Let's say you want to create two functions that take the same parameters and output text in two different ways, for the sake of simplicity you'd want to call them both print().
Since they both take the same parameters, there is no chance for function overloading here, but if you put each function in a separate namespace and then you call print(), you can simply change what the function will be doing by calling a different namespace each time.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am finding my naming conventions rather bothersome. I seem to be re-using the child specific names too much. In my Example below, I have a Widget which has-a Connection which has-a Config. Each of these objects has specialized classes for Foo and Bar types.
So my FooWidget has-a Foo-Connection which has-a Foo-Config. The same for Bar. In C++ I've ended up with nine different header files.
widget.h
connection.h
config.h
foo_widget.h
foo_connection.h
foo_config.h
bar_widget.h
bar_connection.h
bar_config.h
I cant help but look at this a feel like it isn't right. My instincts tell me something needs to be changed. It's like there is a design pattern somewhere to be taken advantage of. But I can't find a better solution.
So I guess my question is the following: Is there a design pattern that will improve this design?
-- I am having difficulty wording my question correctly. Please excuse me, I will update as the question itself becomes more clear.
I don't think there is anything wrong with the structure of your classes but without seeing what these classes do it is going to be hard to give advice on how to improve your design.
I think it is good style to have one header file per class. It makes things easier to find and you can easily use directories (or filters in your IDE) to organise your files. For example you may find it easier to structure your files:
|--Foo
|--foo_widget.h
|--foo_connection.h
|--foo_config.h
|--Bar
|--bar_widget.h
|--bar_connnection.h
|--bar_config.h
|--widget.h
|--connection.h
|--config.h
First of all, there's nothing wrong with doing things that way. Many like to put one class per header, in general. If you don't like looking at so many headers you might organize them by directory, or project tree filter, etc.
This is all a question of style. As long as functionality is untouched, the best option is a function of that funny feeling you have, and same for the folks supporting your code down the road. Maybe this answer can make that funny feeling go down for you, or maybe not.
Second, this very much depends on the use of each class. If the Foo and Bar classes are small, they can be put in the header that contains the encapsulating class. Perhaps add a forward declaration for the sake of the parent class, and finish declaring it at the bottom of the header. Bonus points if they're all related (for example FooConnection is a subclass of Foo) because this shortens declaration space.
If they're relatively small classes, there may be no harm in declaring the Foo and Bar classes within the definition their base class. Then there is no FooConnection--it's actually a Connection::FooConnection. In this case Connection doesn't just define the base for FooConnection, it owns its very definition. That means every time you use a FooConnection in your code, you are thinking in the context of a Connection. I rarely do this myself, primarily because I don't like typing Connection:: all the time, but also because there are so few cases where I only use a class in one context.
If the encapsulated classes are protected or private, then they're only used by the parent class itself (and friend classes and maybe subclasses, what have you). Then, since limited context is established, and if the class declarations are small (<50 or <100 lines), you can declare FooConnection and BarConnection within Connection and still maintain readability.
Bonus point: if you do end up declaring classes inside classes, you might take advantage of namespace separation. I don't know the uses of these classes, but I'm guessing FooConnection isn't a connection itself, but a Foo that belongs to a Collection. So then you might declare a Foo and a Bar class for each of Widget, Connection, and Config.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Well, this is a pretty trivial question. But i'd like to know if it is okay to put multiple classes into one header / source file. I've often enough seen that for every class there is another header and another source file, like it is in Java (not only by Convention...)
I see the ups and downs here: on the one hand you might want to have some relevant classes on one place for editing, since big projects sometimes require you to search a bit for them. On the other hand, more files make single files less heavy, so you don't have to scroll down tousands of lines to get to the method you're searching.
Now what do the Conventions say about that?
[Example]
At the moment i have 3 classes in one file: a Server, A ClientHandler for the Server and a ServerManager.
The server manages the connections, the ClientHandler manages all in- and outgoing traffic for each client and the ServerManager contains some logic i need to run the Server.
[Edit] be gentle with my abilities of the english language, i'm foreign ;)
It's considered good form for each class to have its own header/implementation pair.
The most compelling reason (for me) is that the files are named after the class they contain. This makes it easy to find the correct file for a declaration in the code. If a file has more than one type in it, it becomes harder to name, and therefore harder to maintain.
However, sometimes it's not so clear cut. A "main" class might have some other supporting class that's definitely part of its interface (in the Herb Sutter sense of interface), but doesn't rightly belong as a nested type. This should be rare, but such a case might justify having more than one class per file.
If you've gone to the trouble of abstracting out concepts (such as in the example you give), why not go the extra little bit and put them in their own files? You will thank yourself for it down the line!
There's no real rule, other than common sense. If two classes
are closely linked, it's common to put them in the same header.
And of course, not everything in C++ is a class; free functions
may be grouped in various different headers according to
whatever seems most logical.
Also, there isn't always a one-to-one relationship between
headers and source files. If your class is a template, there
may not be a source file at all. On the other hand, if you're
writing a library that will be widely used, and the class isn't
polymorphic, you'll probably want to put each function in
a separate source file.
And a lot of classes are defined directly in source files, and not in headers.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In Grails, there are two mechanisms for modularity in the view layers: Template and TagLib.
While I am writing my own Grails app, I am often facing the same question when I need to write an UI component: do I need to use a template or a TagLib?
After searching the web, I didn't find a lot of best practices or rules of thumb concerning this design decision, so can you help me and tell me:
What is the main difference between the two mechanisms?
In which scenarios, do you use a TagLib instead of a Template (and vice-versa) ?
There is definitely some overlap, but below are several things to think about. One way to think about it is that Template is like a method-level reuse, while TagLibs are more convenient for API-level reuse.
Templates are great for when you have to format something specific for display. For example, if you wan to display a domain object in a specific way, typically it's easier to do it in a template, since you are basically just writing HTML with some . It's reusable, but I think its reusability in a bit limited. I.e. if you have a template, you'd use it in several pages, not in hundreds of pages.
On the other hand, taglibs is a smaller unit of functionality, but one you are more likely to use in many places. In it you are likely to concatenate strings, so if you are looking to create a hundred lines of HTML, they are less convenient. A key feature taglibs allow is ability to inject / interact with services. For example, if you need a piece of code that calls up an authentication service and displays the current user, you can only do that in a TagLib. You don't have to worry about passing anything to the taglib in this case - taglib will go and figure it out from the service. You are also likely to use that in many pages, so it's more convenient to have a taglib that doesn't need parameters.
There are also several kinds of
taglibs, including ones that allow
you to iterate over something in the
body, have conditional, etc - that's
not really possible with templates.
As I said above, a well-crafted
taglib library can be used to create
a re-usable API that makes your GSP
code more readable. Inside the same *taglib.groovy you can have multiple tag definitions, so that's another difference - you can group them all in once place, and call from one taglib into another.
Also, keep in mind that you can call up a template from inside a taglib, or you can call taglibs withing templates, so you can mix and match as needed.
Hope this clears it up for you a bit, though really a lot of this is what construct is more convenient to code and how often it will be reused.
As for us...
A coder is supposed to see specific object presentation logic in template, not anywhere else.
We use taglibs only for isolated page elements, not related to business logic at all. Actually, we try to minimize their usage: it's too easy to write business logic in a taglib.
Templates are the conventional way to go; for instance, they support Layouts (btw, they can be named a third mechanism)
I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?
Hierarchical namespaces do have a use in that they allow progressively more refined definitions. Certainly a single provider may produce two classes with the same name. Often the first level is occupied by the company name, the second specifies the product, the third (and possibly more) my provide the domain.
There are also other uses of namespace segregation. One popular situation is placing the base classes for a factory pattern in its own namespace and then derived factories in their own namespaces by provider. E.g. System.Data, System.Data.SqlClient and System.Data.OleDbClient.
Obviously it's a matter of opinion. But it really boils down to organization. For example, I have a project which has a plugin api that has functions/objects which look something like this:
plugins::v1::function
When 2.0 is rolled out they will be put into the v2 sub-namespace. I plan to only deprecate but never remove v1 members which should nicely support backwards compatibility in the future. This is just one example of "sane" usage. I imagine some people will differ, but like I said, it's a matter of opinion.
Big codebases will need it. Look at boost for an example. I don't think anyone would call the boost code 'insane'.
If you consider the fact that at any one level of a hierarchy, people can only comprehend somewhere very roughly on the order of 10 items, then two levels only gives you 100 maximum. A sufficiently big project is going to need more, so can easily end up 3 levels deep.
I work on XXX application in my company yyy, and I am writing a GUI subsystem. So I use yyy::xxx::gui as my namespace.
You can easily find yourself in a situation when you need more than one level. For example, your company has a giant namespace for all of its code to separate it from third party code, and you are writing a library which you want to put in its own namespace. Generally, whenever you have a very large and complex system, which is broken down hierarchically, it is reasonable to use several namespace levels.
It depends on your needs and programming style. But one of the benefits of namespace is to help partition name space (hence the name). With a single namespace, as your project is increases in size and complexity, so does the likelihood of name-collision.
If you're writing code that's meant to be shared or reused, this becomes even more important.
I agree for applications. Most people that use multiple levels of namespaces (in my experience) come from a Java or .NET background where the noise is significantly less. I find that good class prefixes can take the place of multiple levels of namespaces.
But I have seen good use of multiple namespace levels in boost (and other libraries). Everything is in the boost namespace, but libraries are allowed (encouraged?) to be in their own namespace. For example - boost::this_thread namespace. It allows things like...
boost::this_thread::get_id()
boost::this_thread::interruption_requested()
"this_thread" is just a namespace for a collection of free functions. You could do the same thing with a class and static functions (i.e. the Java way of defining a free function), but why do something unnatural when the language has a natural way of doing it?
Just look at the .Net base class library to see a namespace hierarchy put to good use. It goes four or five levels deep in a few places, but mostly it's just two or three, and the organization is very nice for finding things.
The bigger the codebase the bigger the need for hierarchical namespaces. As your project gets bigger and bigger you find you need to break it out in ways to make it easier to find stuff.
For instance we currently use a 2 level hierarchy. However some of the bigger portions we are now talking about breaking them out into 3 levels.