How to avoid having the same name for a class and

2019-01-18 10:23发布

问题:

I am frequently having naming conflicts between a namespace and a class within that namespace and would like to know a best practice for handling this when it seems to make sense to use these names in the first place, besides adding random prefixes.

It seemed to make sense to have a Models.Technology namespace, with dozens of technology classes (ie. Weapon, Agricultural, Recycling technologies) and some related interfaces in it. I also decided to have a Technology abstract class, in the Technology namespace, from which all technologies derive.

However, this is forcing me to use code like this:

public Technology.Technology research(Technology.Technology tech) {...}

and likewise:

public Building.Building build(int count) {...}

By the way I did not name my namespace Technologies since I use that term elsewhere as a wrapper for a list of available technologies...

回答1:

Without more precise indications on when you encounter this problem it's hard to give you some general advice.

But I'm gonna suppose you have this problem when you have a base class in your namespace, with others classes inheriting from it. If that's the case you could call your class BaseTechnology (base class) or AbstractBuilding (abstract class) or IAnimal (interface). This even give you more clarity since you specify in the name of your type something important about it.



回答2:

Well, whether your name your namespaces like that nsMyNamespace or you name you class cMyClasse. I'm personnaly in favor of naming the namespace, because it's not something you use a lot in code.

You can also use TechnologyBase or AbstractTechnology for naming your main abstract class that conflict with the name of your namespace, which is what i recommend to keep the most logical naming convention.



回答3:

One general cop-out is to name your namespace "Entities" or something.



回答4:

Another cope out, just call the namespace after the name of the company you are working for.



回答5:

What about Technology.Tech

or:

HumanBeing.Human

or:

CocaCola.Coke ?

What I like to do is have a simple rule. Where I use the first two letters of a word, followed by the last two letters of that word like:

Technology.Tegy

It may not make any sense, but because the same rule always applies, it means less confusion, and there's no need to remember much, except for that one rule. This is just my preference. I, myself like things to look cryptic, so if that's not your style - then maybe this answer isn't for you.

I hope this helps... Atleast a little... :)