简体   繁体   中英

Why should a type not depend on types from its containing namespace?

Also posted here, but with no real academic answer: why namespace types should not depend on nested namespaces types?

If I understand it correctly, the point is that a type Product.Business.Modules.Module can depend on Product.Business.Product , but not the other way around, because Product is the foundation for Module . However, looking at my project structure, I violate this guideline:

namespace Product.Business
{
    using Modules;

    class Product
    {
        public IEnumerable<Module> Modules { get; }

        // Module is abstract, with many different kinds defined in Modules.
    }
}

However, I would like to extend the question.

  1. Where can I find supporting information to back this guideline?
  2. Why is this bad practice?
  3. Is it valid to have types depend on types from other namespaces with the same containing namespace? (eg Product.Business.Security depending on types in Product.Business.Modules ?

In a sense violating this guideline creates a sort of circular namespace dependency, but I'd like to understand more of the why of this guideline rather than just a blanket statement. The only other information I was able to find was from the linked Msdn article. This can actually change the architecture and layout of a class library significantly.

To start with, I'll address your 3rd question. I have not seen any advice against that and seems to be a reasonable thing to do. You separate namespaces logically and one branch of your code might make use of another.

When it comes to nesting the namespaces however, you are creating a hierarchy. As a hypothetical example, consider a company that is testing out some data tools they are developing: Company.Data will have abstract classes and base classes that Company.Data.SqlServer will depend on. SqlServer provides specific implementation for the abstract stuff in the containing namespace. Due to feedback or the need to support another database system, the time may come when for maintainability, they decide to move the SqlServer classes out to a different library.

It is trivial to make the new assembly reference the original Company.Data and go on. The classes in Company.Data will proceed as though nothing changed. If, however, they had dependencies on the contained namespace and/or its classes, doing so breaks Company.Data. It will defeat the purpose of separating concerns. That would mean if they make a product to support MySQL, Company.Data.MySql would have a dependency on Company.Data.SqlServer .

Techniques such as the Provider Model design Pattern will no longer be possible or viable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM