Declare types in namespaces
Types outside any named namespace live in the global namespace (the anonymous namespace), which cannot be referenced in code: naming collisions, ambiguity, and no encapsulation of related code and data. This rule warns about anonymous namespaces.
How to fix
Declare all types of anonymous namespaces in named namespaces.
CQLinq source
This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.
// <Name>Declare types in namespaces</Name>
// <Id>ND1307:DeclareTypesInNamespaces</Id>
warnif count > 0 from n in Application.Namespaces where
// If an anonymous namespace can be found,
// it means that it contains types outside of namespaces.
n.Name == ""
// Filter anonymous namespaces that contains
// only notmycode types (like generated types)
// and also entry points.
let childTypes = n.ChildTypes.Where(t =>
!t.IsNested &&
!t.Methods.Any(m => m.IsEntryPoint) &&
JustMyCode.Contains(t) &&
!t.IsGeneratedByCompiler &&
// Don't match marker classes
!(t.IsSealed && t.Members.Count() == 1 &&
t.Members.Single().IsMethod &&
t.Members.Single().AsMethod.IsConstructor &&
t.Members.Single().AsMethod.NbParameters == 0)
)
where childTypes.Count() > 0
select new {
n,
childTypes,
n.NbLinesOfCode,
Debt = 2*childTypes.Count().ToMinutes().ToDebt(),
Severity = Severity.Medium
}
//<Expl>
// The *{1}* {1?is:are} declared in the global anonymous namespace
// that cannot be imported via a *using* clause.
// This results in naming collisions and ambiguity since
// {1?this type is:these types are} accessible from anywhere.
//</Expl>
//<Desc>
// Types outside any named namespace live in the *global namespace* (the
// *anonymous namespace*), which cannot be referenced in code: naming
// collisions, ambiguity, and no encapsulation of related code and data.
// This rule warns about *anonymous namespaces*.
//</Desc>
//<HowToFix>
// Declare all types of anonymous namespaces in named namespaces.
//</HowToFix>
Open in the interactive Rules Explorer · All default rules
Design: all 16 items
- Avoid custom delegates ND1300
- Types with disposable instance fields must be disposable ND1301
- Disposable types with unmanaged resources should declare finalizer ND1302
- Methods that create disposable object(s) and that don't call Dispose() ND1303
- Disposable Types Must Unsubscribe Events ND1315
- Classes that are candidate to be turned into structures ND1304
- Avoid namespaces with few types ND1305
- Nested types should not be visible ND1306
- Declare types in namespaces ND1307
- Empty static constructor can be discarded ND1308
- Instances size shouldn't be too big ND1309
- Attribute classes should be sealed ND1310
- Don't use obsolete types, methods or fields ND1311
- Do implement methods that throw NotImplementedException ND1312
- Override equals and operator equals on value types ND1313
- Boxing/unboxing should be avoided ND1314