Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can class in parent namespace access class that is in child namespace

Tags:

namespaces

c#

I have a Device class that is in namespace Proj.Devices. Can this class access Message class that is in namespace Proj.Devices.Messages. Both classes are in the same project. I am not asking if this is possible, but whether is this a bad practice?

I think that there will be problems with cyclic references if I split this project to separate projects but otherwise is this ok?

Edit: I have found this on Namespace Naming Guidelines

"A nested namespace should have a dependency on types in the containing namespace. For example, the classes in the System.Web.UI.Design depend on the classes in System.Web.UI. However, the classes in System.Web.UI do not depend on the classes in System.Web.UI.Design."

like image 870
userx01233433 Avatar asked Aug 09 '13 11:08

userx01233433


2 Answers

I can't agree with Morbia. Namespaces are not just here for grouping, they are logic separations (components) where assemblies are concrete separations (layers and concerns).

They are also often seen as hierarchical. Philosophically, something lower in a hierarchy exists through its parent which can exist without this particular child element.

I think this is why the Core namespace exists nowadays. The base namespace is only the base structure / the foundations.

If a sub-namespace is used by its base namespace, you can be sure that a mutual dependency will exist in most cases : this reveals an architecture hazard.

It should be avoided because :

  • Dependencies madness :
    • Mutual dependencies
    • Your base namespace can't exist without a sub-namespace
    • Everything referencing the base namespace can't exist without this sub-namespace and etc...
  • The debug steps will be less understandable
  • The stacktrace will be less understandable

If you don't care about architecture, it is not a problem. But if you are asking yourself this question, you are already thinking about writing good code -which mean with new usages incoming and not only for yourself ;)-.

This is why such practices exists to avoid high coupling :

  • Interfaces
  • Extensions methods
  • Virtual/override

Architecture is about time and not only beauty. At a certain maturity, architecture-less code is less maintainable, less understandable and less scalable.

like image 192
JoeBilly Avatar answered Sep 28 '22 08:09

JoeBilly


Yes they can, namespace is just grouping of classes. No it is not bad practice it is a normal scenario.

If classes from both namespace references each other its not good idea to have them in separate project, as long as they are in same project it is fine.

like image 33
Morbia Avatar answered Sep 28 '22 07:09

Morbia