I have a C# class library shared among several applications. The library is divided into a few smaller components which have dependencies shown in the picture below. Each component is placed in its own namespace to enforce the component boundaries:
Core <- Component A <---- Component B <----- Application
^ ^------ Component C <---/
--- Component D <--/
Now I am thinking about the namespace hierarchy. So far I have found two different approaches:
-
Nested namespace extends the parent namespace, so that the parent namespace can exist without the child components. Alternatively the nested namespace contains implementation of the interfaces from the parent namespace. I believe this approach is used in standard .NET libraries.
-
Parent namespace acts as a mediator which interconnects nested namespaces to form the whole application/super component (described in this article).
Question: Shall the namespace (and folder) hierarchy reflect the namespace dependencies? What is the preferred way of dealing component/namespace dependencies in large projects?
Namespaces provide context in order to name things. They also provide means to avoid conflicts when two different organizations make the name.
- CompanyA.File
- CompanyB.File
In this case, both use File but one can reference both in your application without conflict.
Usually a hierarchy is made in order to provide a means to classify components. Examples:
- Company.Core.Http
- Company.Core.Error
And then
- Company.CoolApp.Dto.Product
Here I have a created a hierarchy to define core components as well as a hierarchy for an application as well.
Usually these hierarchy’s are made up ahead of time and have some sort of convention to it. There is no right or wrong here.
But usually the first level is your ID, second level Common/Core or Application, and 3rd and beyond would be the hierarchy of components that are developed. This would also depend on how your company is structured as well.
Usually the top layer is what identifies you or your org. Under that it is usually grouped by core or common and then by application. As teams write code, components may be moved if an application component is deemed to be a common or core component.
Usually components that are cross cutting are in common or core. These include error handling, logging, etc.
Application components are specific to the application and are usually defined by the development teams. If an application uses Dto or Model as classes to define entities one might what to develop namespace standards that go across applications or products. For example, all entity classes go under a namespace called Model
. Then you have some consistency across applications.
For example:
- Company.CoolApp.Model.Foo
- Company.CrappyApp.Model.Foo
- Company.CrappyApp.Model.Bar
This allows someone at a high level to determine if:
Company.Core.Model.Foo
…should exist, since they can look across applications and determine if it can be consolidated.
3