2

Currently I'm working on the project that is just born. Previous developers used to name each class prepending a shorten vendor name i.e. CssMainWindow. (Css stands for Cool Software Solutions).

My question is: Shouldn't namespaces be used here? Then names of classes become much nicer.

That is:

namespace Css {

    class MainWindow {
        //...
    };
}

What are the (ad|dis)vantages of both methods?

Roman Byshko
  • 8,591
  • 7
  • 35
  • 57

4 Answers4

1

Appending a prefix makes the class name longer and it takes longer to type. That's the only disadvantage I can think of.

Using namespaces.... well you can just put

using namespace Css;

at the beginning of your files and file origin will be lost along with that.

I guess in the end it's up to the developer. There are 2 reasons I can think of why someone would want to identify classes:

1) For a sense of ownership. In that case, appending a prefix is, IMO, the way to go. People using your code will know it's YOUR code :).

2) For grouping classes together - in which case a namespace makes more sense.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

It would depend. If your vendor-specific classes include some things like e.g.

  • tuple, make_tuple
  • string, vector

you may well wish to prefix, so as to prevent ugly ADL clashes1, and general inconvenience when people are expected to be using using namespace XXX. Popular libraries already have used that strategy (XString (Xalan), QString (Qt), CString (MFC) etc)


1 What are the pitfalls of ADL?

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
1

My suggestion: Always use namespace!

I will show several advantages of namespace:

// MainWindow.h
namespace Css {
  class MainWindow {
    // ...
  };
}; 

// Other.cpp
namespace Css {
  // An advantage is you don't always need to write the namespace explicitly.  
  MainWindow* window; // Not Css::MainWindow or CssMainWindow. 
}

// In some cpp files
using namespace Css; // Never do this in header file or it will cause name pollution. 
MainWindow* window; // You don't need to write Css:: in the whole file. 

I can't recall any disadvantage of using namespace.

miaout17
  • 4,715
  • 2
  • 26
  • 32
1

First things first.

Whatever the final choice, you should avoid as much as possible writing anything in the global namespace. You risk to face name clashes there. Therefore, your software should always be in a namespace of its own, and it's better if the name differs from those used in the libraries you depend of (reminder std is reserved already).

Once you have this namespace, then you normally don't need prefixing any longer. At least, not with the project name.

However it is mostly a matter of taste, and I have seen argued in the past that it made it easier to immediately identify where the class came from in the absence of IDE... I personally consider it and outdated habit inherited from C.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722