Coding Standards – Giving Multiple Classes in a Single Library the Same Name

coding-standardsnaming

The project that raised this question is in C#, but it could apply to most languages that use namespaces.

I've read many things on good naming practices:

  • "Don't prefix your class names with their namespace name. That's just creating unnecessary duplication." (Smurf naming)

  • "One of the uses for namespaces is separating code and name collisions. Use them that way."

  • "When I'm reading code from a project and come across a class name, I want to know exactly which class is being referenced and not have to check which namespaces have been imported."

What I haven't been able to figure out is the best way to name classes in namespaces that perform similar tasks, but are completely independent from each other.

For example, let's say I have an audio codec library. The code in each codec namespace is not dependent on the others, but they all depend on a namespace containing common, generic code.

I might have classes like these. (Don't read too much into the names, they're only examples.)

Vorbis codec:

Project.Vorbis.VorbisEncoder
Project.Vorbis.VorbisDecoder
Project.Vorbis.VorbisFrame
Project.Vorbis.VorbisChannel
Project.Vorbis.VorbisParameters

ATRAC3+ codec:

Project.Atrac3P.Atrac3PEncoder
Project.Atrac3P.Atrac3PDecoder
Project.Atrac3P.Atrac3PFrame
Project.Atrac3P.Atrac3PChannel
Project.Atrac3P.Atrac3PParameters

IMA ADPCM codec:

Project.ImaAdpcm.ImaAdpcmEncoder
Project.ImaAdpcm.ImaAdpcmDecoder
Project.ImaAdpcm.ImaAdpcmFrame
Project.ImaAdpcm.ImaAdpcmChannel
Project.ImaAdpcm.ImaAdpcmParameters

Is this good design, or is it too repetitive? I don't like repeating the namespace name in the class name, but I don't know if that's preferable to duplicating class names like this:

Project.Vorbis.Encoder
Project.Atrac3P.Encoder
Project.ImaAdpcm.Encoder

Best Answer

As usual, that depends. It depends on the places where the unprefixed class names can be used. [Disclaimer: I'm a Java freak, but I think my experience will be applicable to C# as well.]

My rule of thumb is that symbols that are visible outside of their home namespace should have a unique name over all namespaces of the project.

If references to some Encoder will only show up in classes from the the same namespace, then, as a reader of the code, I'd expect the Encoder name to stand for the local one. In Java, I'd give the Encoder class a package-local visibility.

But if the Encoders are visible outside of their home namespace, I'd go for the long names.

E.g. Java has a negative example with the classes java.util.Date and java.sql.Date, which sometimes I had to use in the same method (bridging between core algorithm and database) - that forced me to use fully-qualified classnames at least for one of them :-(.