Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace vs nesting class [duplicate]

I am considering these two scenarios:

class StructuralCase
{
   class Structure
   {
       ...
   }
   class Material
   {
       ...
   }
   class Forces
   {
       ...
   }
}

and

namespace StructuralCase
{
   class Structure
   {
       ...
   }
   class Material
   {
       ...
   }
   class Forces
   {
       ...
   }
}

The thing is that inside "StructuralCase" I won't be declaring any instance variables, e.g., it will function as a "parent" for the rest of classes.

This lead me to consider converting StructuralClass to a namespace. What do you think about that? Is there any hard rule?

like image 428
Jose Lopez Garcia Avatar asked Dec 18 '14 21:12

Jose Lopez Garcia


1 Answers

Generally, you want to use a namespace, if only because it enables using statements - otherwise you have to refer to the class by all nested classes (except inside the parent class itself, of course). Thus in case 1, outside reference would have to say

StructuralCase.Structure s = ...

instead of

using StructuralCase; 
// ...
Structure s = ...

Functionally the only real reason to make a nested class is

  • So that the nested type has access to nonpublic members of the parent type. If this is a concern over API surface, see instead internal
  • So that the subclass isn't accessible outside the parent class, such as a specific struct used for results of a specific query
  • So that the child class can share some Generic Parameters from the parent class, such as factory classes which need the same generic parameters
like image 135
David Avatar answered Sep 17 '22 15:09

David