Namespace and Class Name Guidelines in C#

Architecturec

I'm having problems naming my classes and services correctly when utils and other help classes are involved.

How would you structure the following:

EventService.cs
EventServiceUtils.cs
EventServiceValidators.cs
EventServiceCoordinator.cs

etc…

I have multiple services with the same needs as the above service. One thought is to separate all of this into a suitable namespace, making it look something like this:

Services.EventService.EventService.cs //(the actual service)
Services.EventService.Validators.DateValidator.cs
Services.EventService.Validators.ParticipantValidator.cs
Services.EventService.Coordinators.ParticipantCoordinator.cs
Services.EventService.ExtensionMethods.Extensions.cs

and so on. Every namespace is of course a separate folder. But this doesn't feel 100%, since there are probably more DateValidators in the other services, which can easily lead to an unwanted reference.

And also the Services.EventService.EventService.cs includes the class name in the namespace, which is no good either. You could use Services.Event.EventService.cs, but there is of course already an entity with that name.

This is the domain model.

Best Answer

I think the single biggest thing you could do to improve your namespacing here is to remove Service from your EventService namespace. I'd also adjust the namespaces to be more like this:

Services.Events.EventService.cs //(the actual service)
Services.Events.EventExtensions.cs
Services.Events.ParticipantCoordinator.cs
Services.Validators.DateValidator.cs
Services.Validators.ParticipantValidator.cs

I still think that could use some improvement though.

I used to like namespaces, but nowadays I think less is more. Deeply nesting your namespaces can make your code too verbose, and breaking things down to far reduces your ability for inheritance. In your code for example, a DateValidator class could easily be used elsewhere, so it shouldn't have many namespaces above it, since services other than the EventService can now take advantage of a DateValidator class. The same applies to the extension methods. There's no time (that I can see) where you'd need to see all your extension methods at the same time, therefore it makes more sense to group it with the thing that it relates to. In this case, EventExtensions probably links to your EventService, so logically they should sit together in my opinion.

Related Topic