Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace correctness

Tags:

I'm trying to question my own code correctness on the following minimalist example in which a header file lifts a identifier into the current namespace.

#include <string>

namespace mine {

    using std::string; // std::string lifted into mine

    struct agent
    {
        string name;
    };
}

This is a suggestion I made recently as another alternative to the use of a typedef:

#include <string>

struct agent
{
    private:
        typedef std::string string;
    public:
        string name;
};

I considered the first option more correct since it makes use of my own namespace and this is a practice that one should get used to (that of namespace creation and management). Meanhile, since the identifier is being lifted inside a namespace I control, it makes this a safe approach.

However, I'm having second thoughts. For one, careless use of the namespace mine, with a using directive for instance, will also bring std::string into view. Another problem is I'm exposing std::string too much. Perhaps even to areas of the namespace mine where it isn't necessary or desirable.

It's seems to me more correct to always work at the lowest possible scope and work up from there. Expose only the absolutely necessary. The fact I make the typedef private on the second example was exactly because of this. But then I don't follow my own advise with the second example.

But on the other hand, my concerns result from the fact someone might misuse the namespace mine:

using namespace mine;

At first glance, we know this is not a correct usage pattern for a namespace. But it can't be denied there are instances when it may be desirable. How valid do you think is the first approach?