Do not name a class the same as its namespace, Part Four


(This is part four of a four part series; part three is here.)

Part Four: Making the problem worse

I said earlier that the fundamental reason for namespaces in the first place was organization of types into a hierarchy, not separation of two things with similar names. But suppose you are putting something into a namespace because you have two things that are of the same name and need to be kept separate. Suppose you reason “I’m going to put List into its own namespace because List could conflict with another class named List. The user needs to be able to qualify that.”

OK, that’s fine; put List into MyContainers then. But why would you then repeat the process and put List into a child namespace in MyContainers? The most plausible reason is that the level of disambiguation achieved so far is insufficient; some other entity named List is going to be in scope in a code region where elements of MyContainers are also in scope.

Let us posit that as our cause for creating a new namespace MyContainers, and then creating a new sub-namespace, MyContainers.X, to be the declaration space of List. What name should we choose for X? If the whole point is that something else named List is in scope somewhere that elements of MyContainers are in scope, then choosing “List” for “X” is making the problem worse, not better! Before you had two things named List in scope. Now you have three things named List, two of which are in scope. This is making it more confusing without solving the problem at hand: that there are two things named List in scope.

Any one of these four reasons is enough to avoid this bad practice; avoid, avoid, avoid.

(This is part four of a four part series; part three is here.)

Comments (30)

  1. Jerry McGuire says:

    You had me at Do Not Name a Class the Same as its Namespace, Part One.

  2. Gabe says:

    Do you actually see people making singleton namespaces like this? I would have to assume a 4-part series like this wasn’t just brought on by a whim.

    This series is adapted from my review notes for a book that recommended the practice of naming a class after the namespace it is in. I figure if one professional author is doing this on purpose and has been teaching others to do so for who knows how long then potentially thousands of people could be doing it too; I’d like to counter that by spreading the word that this is a bad practice and contrary to our recommendations. (Many of the articles on this blog arise from discussions sparked by errors in books I review.) — Eric

  3. Mark Knell says:

    How do you feel about New York, NY?  The town so nice they named it twice.  Apparently that’s not too predictive of a city’s character, though: Juarez, Juarez is the reigning murder capital of the world.

    There was an obituary a year or two ago of an academic with a famously quick wit.  He was in the audience when an lecturer on linguistics noted that while the world’s languages were full of examples of double negatives being used as affirmative statements, there were no known instances of doubled affirmatives that conveyed a negative.  The academic piped up, “Yeah, right.”

    I also find it amusing that the established linguistic term for doubled words, phonemes, etc., is “reduplication”.

    I could go on, but I’ve got to get my Agile tasks done-done.

    Net net, I quite enjoy reduplication. If Boutros Boutros Ghali ever gives a talk in Walla Walla Washington I’m totally there.

    My favourite reduplication pun is in The Lord of the Rings; you may recall that the Hobbits journey first to the town of Bree, which sits upon Bree Hill, between Chetwood on one side and Coombe on the other. “Bree” is a Celtic word for “hill” and “chet” is a Celtic word for “wood”, so Hill Hill is next to Wood Wood. Had Tolkien only thought to make it “Coombe Valley” then there would be a triple reduplication pun, since cwm is Welsh for “valley”.

     — Eric

  4. Gabe says:

    While we’re redundantly repeating ourselves, one of my favorites is Japanese wagyu beef. In Japanese “wa” means “Japanese” and “gyu” means “beef”, so the term means Japanese Japanese beef beef.

    The Microsoft cafeterias used to advertize sandwiches “with au jus sauce”. — Eric 

    Needless to say, I have a hard time deciding whether I should have Japanese wagyu beef or Mahi Mahi with my couscous when eating in my Rococo dining room. Last time I was in NY, NY, I went to a go-go bar where a girl named Mimi did the Can-Can while wearing a tutu.

    As for you book review notes, I hope your advice was followed. As a technical reviewer it’s sometimes painful to make notes like “this sample doesn’t compile”, only to see the book published with the notes ignored.

    Irregardless, it’s not too hard to imagine a world where the Regex class is in a namespace called System.Text.Regex instead of System.Text.RegularExpressions.

  5. Anthony P says:

    I for one appreciate the series. No, I’d never commit the sin of class X within namepsace X, but the comments provoked thought about other best practices or language standards I was not fully adhering to. Something something about naming collections.

    Now let’s all go listen to Mr. Mister.

  6. Carl D says:

    “… it’s not too hard to imagine a world where the Regex class is in a namespace called System.Text.Regex instead of System.Text.RegularExpressions.”

    I’d rather imagine the world where it was in a namespace named System.Text.Matching or something like that.  There are other members of that taxonomy other than Regex that would fit into such a namespace, e.g. implementations of soft matching algorithms.

    To my eye, System.Text.RegularExpressions.Regex has always looked redundantly redoubled.

    Many years ago I had a high school English teacher affectionately (or perhaps fearfully) known as “the battleaxe” because of her uncompromising high standards, tough grading and take-no-prisoners attitude towards teaching effective English communication. One particular exchange with the battleaxe is forever burned into my memory:

    Mrs. B:  [addressing another student] See, in this paragraph you’re being redundant.  You’re saying the same thing twice, here and here.

    Eric: Sorry, Mrs. B, I missed that, could you say that again?

    Mrs. B: I said he’s being redun… oh. I get it. Very funny. [She is not laughing. She walks over to my desk and stares down at me, sternly]  Eric, I just want you to know that if I were fifteen years younger or you were fifteen years older, you’d be the man for me.

    Boy, did that ever shut me the hell up.  I was completely dumbfounded.  I had absolutely no response to that.

    One of my old friends from high school is actually now an English teacher at our old school. I told him this anecdote once, and it turns out that the battleaxe is still there and moreover, she remembers this particular interaction. (I am continually amazed at how well teachers remember their former students.  I’m sure she’s had a thousand students since then.)

    Mrs. B, if you’re reading this, I’m twenty years older now.

    – Eric

  7. Aaron G says:

    For maximum vomit-inducing impact, I present you with:

    namespace Class

    {

       class Class

       {

           public int @int;

           public string @string;

           public class @class

           {

               public static Class Class;

           }

       }

    }

    So now we can write the following code:

    Class.Class.@class.Class.@string = Class.Class.@class.Class.@int.ToString();

    You think I’m kidding.  I saw something a lot like this on StackOverflow a few weeks ago.

  8. Josh Smeaton says:

    Thank you for this series. We’re working on a library that our co-workers will be using for quite a few years to come and I happened to name a class the same as the namespace it was in. It took me all of about 30 minutes to change it however, as I had to fully qualify the class with its namespace, and it was getting very very annoying. Thanks for validating my thoughts that the design was wrong wrong wrong.

  9. Tim Long says:

    I completely agree, namespace = class name = bad! BUT – I think I can see how people get nudged into this situation by the Visual Studio tooling.

    Naming guidelines say that you should name your assemblies "Manufacturer.Facility…" and when creating a project, using the same naming is appealing. So I might create a new project and name it "TiGra.Widget". This gives me a project file TiGra.Widget.csproj and a default namespace of TiGra.Widget. So now I go ahead and creat my Widget class, and guess what? My namespace is now the same as my class name.

    I always back out of this situation because it is pure evil, but see how easy it is to get nudged into this?

    Maybe if the tooling detected the ‘.’ in the project name and instead of using the whole name as the namespace, just use everything before the last dot as the namespace, then instead of creating the default ‘Class1′, use the identifier after the last dot as the class name.

    Applying that rule would result in a namespace of "TiGra" and a default first class of "Widget" – probably a lot closer to what the user actually intended.

    Unless I’m the only one who names my projects like that of course ;-)

  10. Mark Knell says:

    There’s a winery here in the Pacific NW called David Hill Winery.  I can’t recall the exact language on their bottles, but it’s to the effect that “David Hill Winery was named after two Oregon pioneers: Henry David, for whom the hill and road we are located on was named, and David Hill.”  I chuckle every time I see a bottle of theirs, to think that having decided to be the namesake of one pioneer, the winery was not content to rest.  They pressed on.  They were, in appropriately multiple senses, overdetermined.

    Now I’ve actually looked them up.  http://www.davidhillwinery.com/pages/history.html The language on their website restates things a bit to start with the names of the road and hill.  It then explains the history of the pioneer David Hill, before wandering back around to note without comment that David Hill Road and David Hill the hill were not named for David Hill but for Henry David.  They are silent on the question of whether Henry David was named for Henry David Thoreau… which brings us to the famously self-undermining reduplication, “Simplify, simplify.”

    My head hurts.

    Indeed. I am reminded of the fact that King County, the county in which Microsoft is headquartered, in 2005 changed its name from King County to… King County. See, King County used to be named “King County” in honour of William Rufus King, a slave-owning Senator from Alabama who served as Vice President of the United States for 45 days before dropping dead of tuburculosis in 1853. The council decided to rename King County to “King County”, so as to honour the Reverend Dr. Martin Luther King Jr., a noted civil rights leader. — Eric

  11. Gabe says:

    I just figured it goes without saying that I eat my Japanese wagyu beef sandwich with au jus sauce. Actually, it’s funny you mention that because I think the person who first brought that "au jus" thing to my attention in 1998 was a Microsoftie from Waterloo. I don’t remember his name but wouldn’t it be ironic if you were him (or even knew them), don’t you think?

    Anyway, I suppose I should say "bye-bye" and go walk my dog Fifi in the muu-muu I got from Pago Pago to the ATM machine so I can enter my PIN number to get some cash money to play Putt-Putt.

  12. Mark Knell says:

    That’s excellent.  King County is dead, long live King County!  

    Riffing off of namesakes and the Hobbit: there was a novel that got some attention a few years ago, "Everything Is Illuminated", by Jonathan Safran Foer.  If you don’t care to read the whole thing, it was first published as a longish piece in the New Yorker, and if you don’t care to read, there was a movie starring Frodo.  Most people think the excerpt was stronger than the book, but the novel’s quite funny, to the extent that a highly anticipated, earnest first novel with Holocaust-related subject matter can be.  Much of it is in the voice of a gonzo Ukrainian tour guide whose mangling of English idiom, when it works, is sidesplitting.  Arriving, finally, at my point: the Ukrainian’s father has a smelly and possibly anti-Semitic dog named Sammy Davis Jr., Junior.  

  13. Mark Knell says:

    Oh, and let’s not forget James James Morrison Morrison Weatherby George Dupree.

  14. nog says:

    Gabe trying so hard at pumping out the doubles haha

    “Ha ha” indeed. — Eric

  15. Pavel Minaev says:

    > My favourite reduplication pun is in The Lord of the Rings; you may recall that the Hobbits journey first to the town of Bree, which sits upon Bree Hill, between Chetwood on one side and Coombe on the other. "Bree" is a Celtic word for "hill" and "chet" is a Celtic word for "wood", so Hill Hill is next to Wood Wood. Had Tolkien only thought to make it "Coombe Valley" then there would be a triple reduplication pun, since cwm is Welsh for "valley".

    A wonderful story coming from an entirely unexpected side! I’ll be looking towards more Fabulous Adventures in Middle-Earth from now on…

    (why, yes, I am a closet MERP player)

  16. Tim Goodman says:

    @Pavel: Eric’s *other* claim to internet fame was having one of the earliest websites devoted to the works of J.R.R. Tolkien.  (I’m no expert on the life and times of Eric Lippert, but I have been reading through the Fabulous Adventures archives … he’s made reference to it at least once before.)

  17. The way I discovered this issue was with the term ‘Service’. I created a namespace to match the component, e.g. ‘CustomerDataService’ and then used that same name as the root implementation class, after it was the type that repesented the ‘NT Service’ concept. I ended up changing the component and namespace to ‘CustomerDataServer’ and left the class name alone. I toyed with other alternative like calling the class just ‘Service’, but it can be awkward in the IDE* when you have many files open all with the same name, e.g. Program.cs.

    *I’m not suggesting you name your classes just to satsify this issue.

  18. Gabe says:

    Aye aye, nog.

    Say, does anybody know what happens when a class is declared not in a namespace?

    The grammar of the language requires that every class be declared in one of three places: in the global namespace (which has no name), in some other namespace, or as a nested class inside some other type declaration. Therefore every class is declared in a namespace, either directly, or indirectly via its outer types. Therefore I do not understand the question; can you clarify it? — Eric

     

  19. Joel F says:

    Reminds me of that immutable generic stack implementation you did some time back during the series of articles on immutability. I used that class in a depth-first topological sorter and had to change the name to ImmutableStack<T> so that it wouldn’t conflict with System.Collections.Generic.Stack<T>.

  20. Anthony P says:

    On the topic of proper coding conventions, I could be wrong but it seems neither FxCop nor StyleCop meets my needs. Is there a way to have FxCop level of enforcement on non-compiled code? For example, ASP.NET source files, or anything that hasn’t been built. StyleCop doesn’t appear to be testing the same things, such as collection naming, for example.

  21. Stuart says:

    Obligatory mention of buffalo.

  22. Stuart says:

    namespace Buffalo {

     public class Buffalo {

       Buffalo.Buffalo buffalo(Buffalo.Buffalo Buffalo) { buffalo(Buffalo); }

     }

    }

    I think that actually ought to compile, although I haven’t tried it. Infinite recursion when run, however.

  23. Stuart says:

    oh no it doesn’t compile, needs a "return" in there. Drat.

  24. Gabe says:

    I was just wondering what happens to a class when you declare it without a surrounding namespace{}. It appears the answer is that it goes in the implicit global namespace.

    The first C# app I wrote was for .Net 1.1, and I forgot to put one of my classes in a namespace declaration. Well, it just so happened that when .Net 2.0 came out, it declared a class by the same name. When somebody ran my app on a computer with .Net 2.0 installed but not 1.1, it ran in the 2.0 CLR and got the new class of the same name.

  25. John says:

    One of the annoying (to me that is) characteristics of VSxxxx is that when you add a folder in a project, Visual Studio defaults classes in the folder to a namespace which ends with the name of the folder.  If a programmer is using the folders for physical (as opposed to namespace) organizational purposes, she/he either has to remove the folder name from the namespace of the new class or add a new using statement to include that folder.  In tools/options, the programmer should be able to limit the default namespace to the project.  

  26. Szindbad says:

    John: I like this feature because the folder structure and namespaces are two independent hierarchies, but this feature is try to make them similar, which is beneficial for project "complexity". Managing one hierarchy instead of two is huge benefit.

  27. Julien Lebosquain says:

    Is there any reason why System.Configuration.Configuration doesn’t follow this rule? It’s always painful to use in code. System.Configuration.Config (or something similar) would have been much better, like there isn’t a System.Text.Regex.Regex for instance.

    My guess — and I emphasize that this is a guess — is that the class in question was invented *before* the framework design guidelines were written. — Eric

  28. Alex says:

    The Los Angeles Angels ought to play nothing but doubleheaders.

  29. Newell Henry Clark says:

    Thanks, man. I just went and renamed my static GameEngine class to GameEngineUpdator. It was originally NewellHenryClark.GameEngine.GameEngine, but now I know better, all thanks to you :D

  30. Stephen says:

    This does make it hard when you want namespaces like this:

    Doctor.Events, Doctor.Services, Doctor.BusinessObjects

    And then in Doctor.BusinessObjects you want a class called Doctor.

    Each namespace is a type of Doctor functionality, but you can't call them that and still have a Doctor class.