C++ Coding Style – Is Nesting Typedefs a Good Practice?

ccoding-style

Let's say I have a namespace my and this namespace contains a class foo.

What should I prefer nesting typedefs into my class or hold it in my namespace?

namespace my {

class foo {
  // some stuff

  // nested one
  typedef bar my_foo_bar;

};

// or namespaced one
typedef bar my_foo_bar;

}

Looking at the std-libs most things are the namespace variant.

(maybe a bad example but…) istream is not nested in iostream (at this point I only mean the way of using -> std::fstream, std::istream, …), so I can use it directly. but also the list of possible functions is quite huge in std::

I could do both. The first variant is more encapsulated but also if I have to much inheritance I have to type a lot (my::foo::inh::and::so::on) if I won't use using [namespace].

First I thought the nested variant is more nice because of the encapsulation of what I want to have in the same "group". I also could do a new namespace inside my, but then I have also to type every time the new namespace (also without using [namespace]).

Best Answer

I think that your choice here depends a lot on context.

As a general set of guidelines, I'd say, in rough decreasing order of importance:

  • you write your code once, and read it one or more times. What do you plan to do with your type? What kind of code will you likely have to write, including it? Optimize for maximum legibility, most of the time.
  • generally, it's better to use the most restricted possible name-space for your typedef. So, if you're only using it inside the class, define it there. If you're looking to access it from other places, that have access to the namespace, leave it outside of the class
  • as a heuristic, in my own work, I find myself placing the typedefs in classes more often than not. So if I'm not entirely sure and under pressure to decide quickly, I start by placing the typedef in the class, and refactor it out if I turn out to be wrong. For you, you can look at surrounding code and copy their decision, for now, if you're in a hurry