Click here to Skip to main content
15,888,521 members
Articles / Programming Languages / C++
Article

Using namespaces properly

Rate me:
Please Sign up or sign in to vote.
3.84/5 (15 votes)
30 Jan 2001 125.1K   51   15
This article does not teach you the syntax of namespaces. Rather, it shows you how to use them properly.

Introduction

Namespaces are a very powerful C++ language feature. This article does not teach you the syntax of namespaces. Rather, it shows you how to use them properly.

Namespaces simply wrap all enclosed names with another name. For example:

namespace net {
    class Socket {
        ...
    };
}

...

net::Socket socket;

By doing that, they make sure that if two libraries both implement the Socket class, if they name their namespaces differently your program can use both without a conflict.

But this brings up another question: If two independent companies both decide to write network libraries, what are the chances that they are going to implement a class named Socket? My guess is somewhere around 100 percent.

We also like it when namespace names are easy to type, which means that they should be 2-4 characters long. With that in mind, what are the chances that both companies are going to name their namespace net? 5 percent? 10 percent?

Whatever it is, it shows that namespaces do not solve the problem, they only make it less severe.

An Industrial Strength Solution

The solution to this problem is to use long, unique namespace names, and then bring the namespaces into a program by using short aliases.

So a company writing the network library should write something like:

namespace net_33843894 {
    class Socket {
        ...
    };
}

where the number after net_ is going to be generated using a random number generator. Say this code is placed in a header file called <netlib>

Then the library is sold to a client, who decides to use it on a project. The client then writes his own project-local header file named <mynetlib>, with the following content:

#include <netlib>

namespace net = net_33843894;

He has just created a project-local alias for the namespace of his library vendor. If the namespace name net had already been taken by another library, the user can choose another name: net2, sock, or something else. There will be no name conflicts.

Lowering Barriers

A smart thing to do with your library is to make it easy for people to start using it. In an ideal world, they should be able to double-click on an installation file and the library would be immediately available inside their development environment. Next thing they are typing is #include <yourlib> and they are using it to do something useful.

However, if the user has to make his own header for every header in your library, then he has to suffer a little bit in order to use it. Not every user will be willing to do so.

The solution to this problem is to provide reasonable defaults, but to let the users cop out of them if they are not suitable. The way to do this is with preprocessor directives in your header file:

namespace net_33843894 {
    class Socket {
        ...
    };
}

#ifndef NO_NET_33843894_ALIAS
    namespace net = net_33843894;
#endif

This way, we provide a reasonable default for the namespace name. If that name is already taken, then the user can define the macro NO_NET_33843894_ALIAS and no alias will be defined.

Current Compilers

Error messages are already a nightmare with templates. With long namespace names, we make them even worse.

Unfortunately, none of the compilers I use are smart enough to display an error with the shortest available namespace alias at the point of error. So even though you may be using the alias net, if you make an error using the Socket class the error will mention net_33843894::Socket. Not very readable.

So I use a little trick. It works only for headers that contain only inline functions (as it affects the actual names used by the linker), but I have plenty of those. If the macro NO_NET_33843894_ALIAS is not defined, I use the short name as the namespace name, and the long name as the alias:

#ifdef NO_NET_33843894_ALIAS
namespace net_33843894 {
#else
namespace net {
#endif
    class Socket {
        ...
    };
}

#ifndef NO_NET_33843894_ALIAS
    namespace net_33843894 = net;
#endif

And the error messages become bearable again.

 

For more good stuff about C++, including a way to write code without memory errors, visit http://www.jelovic.com.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Yugoslavia Yugoslavia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNO!! Don't do this! Just use nested namespaces. Pin
Don Clugston29-Mar-04 12:50
Don Clugston29-Mar-04 12:50 
GeneralRe: NO!! Don't do this! Just use nested namespaces. Pin
AndreRyan29-Feb-08 17:03
AndreRyan29-Feb-08 17:03 
GeneralRe: NO!! Don't do this! Just use nested namespaces. Pin
Member 368078527-Jan-09 11:08
Member 368078527-Jan-09 11:08 
GeneralGreat article for newbies - idea for extension... Pin
Paul Evans12-Dec-02 10:35
Paul Evans12-Dec-02 10:35 
GeneralA better solution to your problem Pin
17-May-01 14:05
suss17-May-01 14:05 
GeneralRe: A better solution to your problem Pin
Dejan Jelovic18-May-01 2:21
Dejan Jelovic18-May-01 2:21 
GeneralHELP ME PLS!!!!!!!!!!!!!!! Pin
7-May-01 6:01
suss7-May-01 6:01 
GeneralRe: HELP ME PLS!!!!!!!!!!!!!!! Pin
7-May-01 6:45
suss7-May-01 6:45 
GeneralRe: HELP ME PLS!!!!!!!!!!!!!!! Pin
ekolis8-Jul-12 13:03
ekolis8-Jul-12 13:03 
GeneralHELP ME PLS!!!!!!!!!!!!!!! Pin
7-May-01 6:01
suss7-May-01 6:01 
Due: 9 May 2001



Objective: Comparing both divide and conquer sorting method using traditional way, by counting the elapsed time, and mathematical way, by counting number of comparisons and movements.
Write a C program of bottom-up non-recursive MergeSort , called function NRMergeSort. You are required to modify the recursive MergeSort program discussed on the class, by removing its recursion of MergeSort, and start do (or call) Merge function from the bottom to the top, as illustrated bellow:



Inside this function or program, count the number of comparisons between entries in the input list. Whenever it is found a comparison between entries increment the comparison counter by one. Also, inside this function or program, Count the number of movements of entries in the input list. Whenever there is movement or assignment from original list to temp array, increment movement counter by one, and whenever there is movement or assignment from temp array to the original list, increment the movement counter by one.

Write a C program of MeanSort, called function MeanSort. This is a modified version of QuickSort program discussed on the class. The modified part is ONLY in choosing the pivot. The pivot of this MeanSort is an average or a mean of an input list or sub-list. Inside this function or program, count the number of comparisons between entry in the input list and the pivot. Whenever it is found a comparison between entry and pivot, increment the comparison counter by one. Also, inside this function or program, Count the number of movements of entries in the input list. Whenever there is swapping between two entries, increment the movement counter by three.

Write a main program, The main program should contain the following:

Interact with user to enter the size of the input list.

Give a user a choice (menu) either to enter the entries of the input list manually (entered by user) or let computer generating entries of random numbers.

Call both NRMergeSort and MeanSort program or function. Record the elapsed time (in seconds) of each function. Start record the time from calling the function until the function is returned.

Print all the statistics or measurement, includes elapsed time, number of comparisons, and number of movements of each NRMergeSort funtion and MeanSort function.

Print the Original (unsorted) list and the sorted list.

Implementation Guidelines:

The type of input list for the above functions is your choice. You may use General list contiguous implementation, or simple array. When you declare it, declare the size of the list or array at least 100.

The comparison and movement counter are recommended to be global variables.

To record the elapsed time, you may use the following function time() in TIME.H library. To get more accurate in measuring the elapsed time (recommended) use the function clock() in TIME.H library.

To generate integer random number use the following functions: randomize(), random(), and rand() in STDLIB.H library.

Bonus 25 Points

Bonus of 25 points is given for those students who extend this program by enabling the program to read the input from a text stream file that consist of lots of (more than 500) integer numbers. And give the flexibility to user to choose the size and the starting record of the file to be retrieved and passed as an input to the above both functions.



Deliverable and Important Note
Hand-in both hardcopy and softcopy (diskette) of program in an envelope at the beginning of class on 9 May 2001.

Make sure you follow the principle of good programming in lecture 2 note.

N0 LATE submission.

Copying other student's work may result 'F' grade on this course.


I NEED HELP PLEASE FROM ANY ONE WELCOMMMMMMMMMMMMMMMMMMMMMMMMME

GeneralRe: HELP ME PLS!!!!!!!!!!!!!!! Pin
1-Jun-01 9:47
suss1-Jun-01 9:47 
GeneralAn alternative to a random number Pin
Jason De Arte31-Jan-01 8:53
Jason De Arte31-Jan-01 8:53 
GeneralRe: An alternative to a random number -- not really Pin
Dejan Jelovic31-Jan-01 10:37
Dejan Jelovic31-Jan-01 10:37 
GeneralSuggestion: URNs as namespace identifiers Pin
Jonathan Gilligan31-Jan-01 13:30
Jonathan Gilligan31-Jan-01 13:30 
GeneralRe: Suggestion: URNs as namespace identifiers Pin
Dejan Jelovic18-May-01 2:31
Dejan Jelovic18-May-01 2:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.