c++ namespace usage and naming rules - c++

On the project we are trying to reach an agreement on the namespace usage.
We decided that the first level will be "productName" and the second is "moduleName".
productName::moduleName
Now if the module is kind of utility module there is no problem to add third namespace. For example to add "str": productName::utilityModuleName::str - to divide space where all "strings" related stuff will go.
If the module is the main business module we have many opportunities and almost no agreement.
For example
class productName::mainModuleName::DomainObject
and
class productName::mainModuleName::DomainObjectSomethingElseViewForExample
can be both at
namespace productName::mainModuleName::domainObject
class Data
class ViewForExample
Why should we create inner not private classes and not namespaces?
Why should we create class where all methods are static (except cases when this class is going to be template parameter)?
Project consist of 1Gb of source code.
So, what is the best practice to divide modules on namespaces in the c++?

What namespaces are for:
Namespaces are meant to establish context only so you don't have naming confilcts.
General rules:
Specifying too much context is not needed and will cause more inconvenience than it is worth.
So you want to use your best judgment, but still follow these 2 rules:
Don't be too general when using namespaces
Don't be too specific when using namespaces
I would not be so strict about how to use namespace names, and to simply use namespaces based on a related group of code.
Why namespaces that are too general are not helpful:
The problem with dividing the namespace starting with the product name, is that you will often have a component of code, or some base library that is common to multiple products.
You also will not be using Product2 namespaces inside Product1, so explicitly specifying it is pointless. If you were including Product2's files inside Product1, then is this naming conversion still useful?
Why namespaces that are too specific are not helpful:
When you have namespaces that are too specific, the line between these distinct namespaces start to blur. You start using the namespaces inside each other back and forth. At this time it's better to generalize the common code together under the same namespace.
Classes with all static vs templates:
"Why should we create inner not
private classes and not namespaces?
Why should we create classes where all
methods are static"
Some differences:
Namespaces can be implied by using the using keyword
Namespaces can be aliased, classes are types and can be typedef'ed
Namespaces can be added to; you can add functionality to it at any time and add to it directly
Classes cannot be added to without making a new derived class
Namespaces can have forward declarations
With classes you can have private members and protected members
Classes can be used with templates
Exactly how to divide:
"Project consist of 1Gb of source
code. So, what is the best practice to
divide modules on namespaces in the
c++?"
It's too subjective to say exactly how to divide your code without the exact source code. Dividing based on the modules though sounds logical, just not the whole product.

This is all subjective, but I would hesitate to go more than 3 levels deep. It just gets too unwieldy at some point. So unless your code base is very, very large, I would keep it pretty shallow.
We divide our code into subsystems, and have a namespace for each subsystem. Utility things would go into their own namespace if indeed they are reusable across subsystems.

It seems to me that you are trying to use namespaces as a design tool. They are not intended for that, they are intended to prevent name clashes. If you don't have the clashes, you don't need the namespaces.

I divide namespaces depending on its usages:
I have a separate namespace, where I have defined all my interfaces (pure virtual classes).
I have a separate namespace, where I have defined my library classes (like db library, processing library).
And I have a separate namespace, where I have my core business (business logic) objects (like purchase_order, etc).
I guess, its about defining it in a way, that doesn't becomes difficult to handle in the future. So, you can check the difficulties that will surround on your current design.
And if you think they are fine, you should go with it.

Related

Plural or singular namespace names in C++

Suppose we have a namespace containing several policy classes:
namespace loggingPolicy {
class OnWrite {...};
class OnReadWrite {...};
etc.
} // namespace
The name LoggingPolicy::OnWrite makes sense. On the other hand, this namespace is really a collection of classes and the name loggingPolicies would reflect that better. Which one should be chosen?
Although I do not generally follow the Google C++ Style Guide, I did look up its naming conventions for namespaces, but it did not have anything to say on the issue.
P.S. I am working on an independent project and am not bound to any organization's guidelines. However, my framework will hopefully be used by many people, so good notation style is important.
There is no technical argument for or against any of this choice. Basically it's a packaging choice, like a library name or a header name.
There are some consistency arguments in favor of the singular if you place yourself on the side of your users:
the user will use your LoggingPolicy framework.
if you'd embed it in its own library, the user will use the Policy library
if you'd expose all your declarations in a unique header, it would be LoggingPolicy.h
if you'd use the plural, it will confuse the user, because he already use the std namespace (and not the stds or standards namespace, even if it encapsulates many different standard areas). Same for headers: all the c++ header names are in singular (e.g algorithm, iterator, string are all in singular despite offering many different algorithms, iterators or strings.
Finally, today you expose only policy classes. But what if you'd expose also some common helper classes, or utility functions ? The plural would then give the impression that these object are alternative policies, while in reality they only complete the policy which it was used for.

Module and Class in OCaml

What are the differences between Module and Class in OCaml.
From my searching, I found this:
Both provide mechanisms for abstraction and encapsulation, for
subtyping (by omitting methods in objects, and omitting fields in
modules), and for inheritance (objects use inherit; modules use
include). However, the two systems are not comparable.
On the one hand, objects have an advantage: objects are first-class
values, and modules are not—in other words, modules do not support
dynamic lookup. On the other hand, modules have an advantage: modules
can contain type definitions, and objects cannot.
First, I don't understand what does "Modules do not support dynamic lookup" mean. From my part, abstraction and polymorphism do mean parent pointer can refer to a child instance. Is that the "dynamic lookup"? If not, what actually dynamic lookup means?
In practical, when do we choose to use Module and when Class?
The main difference between Module and Class is that you don't instantiate a module.
A module is basically just a "drawer" where you can put types, functions, other modules, etc... It is just here to order your code. This drawer is however really powerful thanks to functors.
A class, on the other hand, exists to be instantiated. They contains variables and methods. You can create an object from a class, and each object contains its own variable and methods (as defined in the class).
In practice, using a module will be a good solution most of the time. A class can be useful when you need inheritance (widgets for example).
From a practical perspective dynamic lookup lets you have different objects with the same method without specifying to which class/module it belongs. It helps you when using inheritance.
For example, let's use two data structures: SingleList and DoubleLinkedList, which, both, inherit from List and have the method pop. Each class has its own implementation of the method (because of the 'override').
So, when you want to call it, the lookup of the method is done at runtime (a.k.a. dynamically) when you do a list#pop.
If you were using modules you would have to use SingleList.pop list or DoubleLinkedList.pop list.
EDIT: As #Majestic12 said, most of the time, OCaml users tend to use modules over classes. Using the second when they need inheritance or instances (check his answer).
I wanted to make the description practical as you seem new to OCaml.
Hope it can help you.

Avoiding Over-Use of Namespaces

My library uses several nested namespaces, laid out like the following:
Library name
Class name 1
Class name 2
Class name 3
[...]
Utilities
Class name 1
[...]
Class name 2
[...]
Class name 3
[...]
[...]
The "Utilities" namespace contains useful extensions to each of the classes that don't warrant being included in the actual class itself.
The "Library name" namespace is necessary because it avoids broad conflicts with other libraries, the "Utilities" namespace is necessary to avoid the type of ambiguity that arises from things like this, and the "Class name" namespaces inside it avoid name clashes between utilities written for similar classes.
Despite this, it's still an enormous hassle in practice. Take the following, for example:
MyLibrary::MyContainer<int> Numbers = MyLibrary::Utilities::MyContainer::Insert(OtherContainer, 123, 456);
// Oh God, my eyes...
This makes me think I'm doing something seriously wrong. Is there an easier way to keep things organized, intuitive and unambiguous?
Look at how the standard library (or boost) is organized. Nearly all of it is inside the single std namespace. There's just little to be gained by putting everything inside its own namespace.
Boost puts most things inside boost, while major libraries get a single subnamespace (boost::mpl, or boost::filesystem, for example). And libraries commonly define a single aux subnamespace for internal implementation details.
But you don't typically see deep or fine-grained namespace hierarchies, because they're just painful to work with, and there's little to no benefit from them.
Here are some good rules of thumb:
Helper functions related to a specific class should be in the same namespace as the class, to enable ADL to work. Then you don't need to qualify the name of the helper function at all when calling it. (Like how you can call sort instead of std::sort on iterators defined in std).
For everything else, remember that the purpose of namespaces is to avoid name clashes and not much else. So all your library should be in a namespace, to avoid clashes with user code, but within that namespace, there's no technical need for further subnamespaces unless you plan to introduce clashing names.
You may want to separate internals of your library into a sub-namespace, so users don't accidentally pick them up from the main namespace, similar to Boost's aux.
But generally, I'd suggest as few nested namespaces as possible.
And finally, I tend to make a point of using short, easy-to-type and easy-to-read names for my namespaces (again, std is a good example to follow. Short and to the point, and nearly always without further nested namespaces, so you don't get a cramp from having to write it often, and so it doesn't clutter your source code too much.)
Just the first rule about helper functions and ADL would allow your example to be rewritten like this instead:
MyLibrary::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);
Then we could rename MyLibrary to, say, Lib:
Lib::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);
and you're down to something pretty manageable.
There shouldn't be any clashes between similar utility functions for different classes. C++ allows you to overload functions, and specialize templates, so that you can have both an Insert(ContainerA) and Insert(ContainerB) in the same namespace.
And of course, clashes between namespaces and classes are only possible if you actually have additional nested namespaces.
Remember that within your Library namespace, you alone dictate which names are introduced. And so you can avoid name clashes just by, well, not creating any clashing names. A namespace to separate user code from library code is important because the two may not know about each others, and so clashes can occur unintentionally.
But within your library, you can just give everything non-clashing names.
If something hurts, stop doing it. There is absolutely no need to use deeply nested namespaces in C++ - they are not intended to be architectural devices. My own code always uses a single level of namespaces.
If you insist on using nested namespaces, you can always create short aliases for them:
namespace Util = Library::Utility;
then:
int x = Util::somefunc(); // calls Library::Utility::somefunc()
A declaration in a header file necessitates the namespacing to not pollute the global namespace:
MyLibrary::Utilities::MyContainer<int> Numbers;
But in the source file you can use usings:
using namespace MyLibrary::Utilities;
...
MyContainer<int> Numbers;
Numbers.Insert(OtherContainer, 123, 456);
The fully qualified name doesn't actually look that bad to me, but I like being explicit in method and class names. But using can help things out:
You could probably get away with a using namespace MyLibrary at global scope in your source files, making it:
MyContainer<int> Numbers = Utilities::MyContainer::Insert(OtherContainer, 123, 456);
And then you can import the specific functions you need:
using MyLibrary::Utilities::MyContainer::Insert
and then
MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);

Namespace Class Functions

I have few questions (keeping C/C++ in context)
- When I want to use namespace?
- When I want to use classes inside namespace?
- When I should use functions/routines inside namespace (not inside class)?
Thanks.
When I want to use namespace?
You should use a namespace whenever it helps to organize your code better. You can group related classes, functions, constants, and types together under a single namespace.
When I should use functions/routines inside namespace (not inside class)?
Whenever the function does not need to be a member function. Namely, if a function does not need to access any member variables of any class instance, it should be implemented as a non-member function.
Herb Sutter's Guru of the Week articles What's In a Class? -- The Interface Principle and Namespaces and the Interface Principle discuss the use of non-member functions and namespaces in an interface.
Namespaces provides a way to organize your code, which it is useful for. Namespaces does not provide any extra functionality to C++. If used poorly it tends to the code more complicated to debug. If you decide to use namespaces, try avoid putting "using namespace" in your source files. Never use them in your header files. Point out specific classes instead "using std::vector" or similar, or add the use of "using namespace" inside a scope. This will make all your future use of namespaces much less painful.

When to use Header files that do not declare a class but have function definitions

I am fairly new to C++ and I have seen a bunch of code that has method definitions in the header files and they do not declare the header file as a class. Can someone explain to me why and when you would do something like this. Is this a bad practice?
Thanks in advance!
Is this a bad practice?
Not in general. There are a lot of libraries that are header only, meaning they only ship header files. This can be seen as a lightweight alternative to compiled libraries.
More importantly, though, there is a case where you cannot use separate precompiled compilation units: templates must be specialized in the same compilation unit in which they get declared. This may sound arcane but it has a simple consequence:
Function (and class) templates cannot be defined inside cpp files and used elsewhere; instead, they have to be defined inside header files directly (with a few notable exceptions).
Additionally, classes in C++ are purely optional – while you can program object oriented in C++, a lot of good code doesn't. Classes supplement algorithms in C++, not the other way round.
It's not bad practice. The great thing about C++ is that it lets you program in many styles. This gives the language great flexibility and utility, but possibly makes it trickier to learn than other languages that force you to write code in a particular style.
If you had a small program, you could write it in one function - possibly using a couple of goto's for code flow.
When you get bigger, splitting the code into functions helps organize things.
Bigger still, and classes are generally a good way of grouping related functions that work on a certain set of data.
Bigger still, namespaces help out.
Sometimes though, it's just easiest to write a function to do something. This is often the case where you write a function that only works on primitive types (like int). int doesn't have a class, so if you wanted to write a printInt() function, you might make it standalone. Also, if a function works on objects from multiple classes, but doesn't really belong to one class and not the other, that might make sense as a standalone function. This happens a lot when you write operators such as define less than so that it can compare objects of two different classes. Or, if a function can be written in terms of a classes public methods, and doesn't need to access data of the class directly, some people prefer to write that as a standalone function.
But, really, the choice is yours. Whatever is the most simple thing to do to solve your problem is best.
You might start a program off as just a few functions, and then later decide some are related and refactor them into a class. But, if the other standalone functions don't naturally fit into a class, you don't have to force them into one.
An H file is simply a way of including a bunch of declarations. Many things in C++ are useful declarations, including classes, types, constants, global functions, etc.
C++ has a strong object oriented facet. Most OO languages tackle the question of where to deal with operations that don't rely on object state and don't actually need the object.
In some languages, like Java, language restrictions force everything to be in a class, so everything becomes a static member function (e.g., classes with math utilities or algorithms).
In C++, to maintain compatibility with C, you are allowed to declare standalone C-style functions or use the Java style of static members. My personal view is that it is better, when possible, to use the OO style and organize operations around a central concept.
However, C++ does provide the namespaces facilities and often it is used in the same way that a class would be used in those situations - to group a bunch of standalone items where each item is prefixed by the "namespace" name. As others point out, many C++ standard library functions are located this way. My view is that this is much like using a class in Java. However, others would argue that Java uses classes because it doesn't have namespaces.
As long as you use one or the other (rather than a floating standalone non-namespaced function) you're generally going to be ok.
I am fairly new to C++ and I have seen a bunch of code that has method definitions in the header files and they do not declare the header file as a class.
Lets clarify things.
method definitions in the header files
This means something like this:
file "A.h":
class A {
void method(){/*blah blah*/} //definition of a method
};
Is this what you meant?
Later you are saying "declare the header file". There is no mechanism for DECLARING a file in C++. A file can be INCLUDED by witing #include "filename.h". If you do this, the contents of the header file will be copied and pasted to wherever you have the above line before anything gets compiled.
So you mean that all the definitions are in the class definition (not anywhere in A.h FILE, but specifically in the class A, which is limited by 'class A{' and '};' ).
The implication of having method definition in the class definition is that the method will be 'inline' (this is C++ keyword), which means that the method body will be pasted whenever there is a call to it. This is:
good, because the function call mechanism no longer slows down the execution
bad if the function is longer than a short statement, because the size of executable code grows badly
Things are different for templates as someone above stated, but for them there is a way of defining methods such that they are not inline, but still in the header file (they must be in headers). This definitions have to be outside the class definition anyway.
In C++, functions do not have to be members of classes.