Namespace cohesion
As with any logical grouping of code, what is contained within the grouping may or may not be related. Syntactically, a namespace can contain any number of classes with any number of purposes related to any number of things. Grouping in a namespace is for the programmer; if it doesn't add any value, there's not much point to using it. Classes within a namespace should be related to one another in a particular way that adds value.
Refactoring namespaces with low-cohesion
Unfortunately, there isn't a built-in way to move a class from one namespace to another. You can rename a namespace, but if there is more than one class within the namespace, you "move" all the classes to a new or existing namespace.
Let's say we have a class in the Invoicing namespace, and we want to move it to the Invoicing.Domain namespace because this class represents a fundamental domain entity and locating it in the Domain namespace will mean it will be cohesive with the other members of the Domain namespace.
namespace Invoicing{ /// <summary> /// Address shape to encapsulate /// western-style addresses /// </summary> public class Address { public string Street { get; private set; } public string City { get; private set; } public string Province { get; private set; } public string Country { get; private set; } public string PostalCode { get; private set; } public Address(string street, string city, string province, string country, string postalCode) { Street = street; City = city; Province = province; Country = country; PostalCode = postalCode; } }}
In order to perform a Move to Another Namespace refactoring, right-click the namespace name Invoicing, and select Refactor\Rename… then enter "Invoicing. Domain". This effectively "moves" the Address class to a new namespace, the Invoicing.Domain namespace. This results in the following:
namespace Invoicing.Domain{ /// <summary> /// Address shape to encapsulate /// western-style addresses /// </summary> public class Address { public string Street { get; private set; } public string City { get; private set; } public string Province { get; private set; } public string Country { get; private set; } public string PostalCode { get; private set; } public Address(string street, string city, string province, string country, string postalCode) { Street = street; City = city; Province = province; Country = country; PostalCode = postalCode; } }}
The only "heavy lifting" at this point you'll have to do is move the file this class lives in from one directory to another (if you're synchronizing namespace names with directory names). This can be accomplished by dragging and dropping the file in the Solution Explorer.