Shared classes between namespaces, how to distribute them?
https://softwareengineering.stackexchange.com/questions/377207
Question
Some time ago I read from this book that namespaces inside libraries should be distributed in a way that inner namespaces have more concrete classes than their parent namespaces. We can find an example of this inside the namespace System.Net
, where we can find the class WebClient. This class has a higher abstraction level than Socket which is inside the System.Net.Sockets
namespace (in fact, WebClient
uses Socket
).
My question is, how about all those classes used by the parent and descendant namespaces? In which namespace should I put them? Should I create a new different one called something like Parent.Shared
and import them from Parent
, from Parent.Child
and from Parent.Child.GrandChild
?
Solution
Namespaces are a mechanism to show a correlation between classes. Classes within a namespace should be related to each other and the namespace name should give an indication of the commonality between the classes.
For example, all classes within the System.Net
namespace are networking related classes.
This suggests that it is best to look at namespace names as if they give an organization like library.topic.subtopic
.
Suppose you have the following namespaces
library.topic1
library.topic1.subtopic1a
library.topic1.subtopic1b
library.topic2
It is to be expected that classes in subtopic1a
represent more concrete/detailed concepts than classes in topic1
. That means that it would be strange to see a class in subtopic1a
referencing a class in topic1
, but it would be perfectly normal to see references to classes in subtopic1b
or in topic2
. Namespaces are not so hierarchical that you can only refer to classes in "lower levels".