What should go into the top level namespace? For example, if I have MyAPI.WebLogic, MyAPI.Compression, etc. If I put classes into the top level namespace, am I violating the principle of encapsulation?
Depends on what the namespace is for really. If its an application then perhaps something like bootstrapper classes, loaders etx, Main's etc. I'd say (as with everything) "it depends".
Namespaces are not for OOP related concepts like encapsulation. There for organization, so organize it in a way that what makes sense to your application. Most the work I do on websites has a business library and most often it's all tucked under a single namespace.
I don't think you're really violating encapsulation per se by doing that.
Normally namespaces are just a way to organize your classes to make them easier to find, so whatever makes sense for your app.
You're not violating encapsulation at all as far as I see it. In fact, I'm not even sure this can be called encapsulation, given that namespaces aren't specific to OOP - its rather just the orginsation of types.
The rule is simply to place a type in the top-level namespace if you feel it belongs there. An obvious example for this situation is when (using your examples) MyAPI.WebLogic and MyAPI.Compression (perhaps as well as others) all need to utilise a certain type - it is therefore best just to put this type in MyAPI. If you're still not quite sure what belongs, use the Microsoft libraries as examples. There are plenty of classes in the System
namespace within the BCL!
Depends what the classes are.
One guideline I try to follow is that dependencies between namespaces shouldn't follow a cycle. In other words, low-level namespaces can't access types from higher-level namespaces.
This means that the top-level MyAPI namespace must contain either:
- High-level code: code that's allowed to look inside MyAPI.WebLogic and MyAPI.Compression
- Or, low-level code: code that's used by MyAPI.WebLogic and/or MyAPI.Compression
Patrick Smacchia has written a lot on the advantages of structuring your code in this way, including on this site: http://stackoverflow.com/questions/304967/detecting-dependencies-between-namespaces-in-net