C# namespaces: how to follow standards without causing annoying conflicts? - c#

I'm working on a C# library (let's just call it "Foo" for the sake of this question). It has some needs very similar to standard .NET needs: for example, it provides some drawing services, and some conversion services.
For the sake of familiarity and users of the library being able to guess what things are called, I'd like to follow the .NET standard, and name these parts of the library Foo.Drawing and Foo.Convert (and so on). But I'm finding that in actual use, this causes pain. People almost always have "using System;" at the top of each file, and when using this library, they want to have "using Foo;" as well. But now they have two Drawing and two Convert modules, and hilarity ensues.
For example, now instead of just using Drawing.Color for a parameter or variable type, you have to explicitly spell out System.Drawing.Color, or the compiler complains that Foo.Drawing doesn't have a Color type. Similarly, you want to use a standard Convert.ToInt32, you have to say System.Convert.ToInt32, even though you're already using System, because otherwise it finds Foo.Convert and fails to find ToInt32.
I understand why all this is as it is, but I'm still new to the C# community, so I don't know which is the most standard solution:
Leave it this way, and expect users to use fully-qualified names where necessary?
Rename the conflicting modules to something else (maybe Foo.Graphics instead of Foo.Drawing, and Foo.Conversion instead of Foo.Convert)?
Use some prefix on the standard names (Foo.FDrawing and Foo.FConvert)?
Something else?
Any advice from you more experienced C# gurus will be appreciated!

You can use namespace aliasing :
using System;
using FConvert = Foo.Convert;
public class Bar
{
public void Test()
{
var a = Convert.ToInt32("1");
var b = FConvert.ToInt32("1");
}
}

One of the main usage of namespaces is to avoid name clashing.
It means that namespaces allow developers to create types with identical names, as long as the belong to different namespaces.
A library usually have at least a root namespace, and possibly nested namespaces that logically groups the related types.
Name your types as you wish, as long as the names are meaningful and represent what the type really are. A client of your library expects a type named Animal to represent an Animal, not something else. The same applies for naming namespaces.
However, avoid at all cost the names from System, since it will be really annoying for your library clients (as you described) to deal with conflicting names all over the place.
A common way to deal with conflicting namesapces inside a class is to use namespace aliasing:
using FooConvert = Foo.Convert;
using BarConvert = Bar.Convert;

Related

Naming convention: How to name a different version of the same class?

I have a class MyClass which has a bug in the implementation. The class is part of a library, so I can't change the implementation of the class because it will silently change behavior for existing clients (clients who in this case may rely on the bug: See for example (https://connect.microsoft.com/VisualStudio/feedback/details/790160/httpclient-throws-operationcanceledexception-insead-of-timeoutexception))
I need to create a second version of the same class which includes the bug fix.
I've seen situations like this before but the naming I've seen was always incremental Eg MyClass2 , MyClass3.
These cases are probably quite rare, however I was wondering if there is a better way of naming these "versioned" classes.
I imagine a solution which grows in time and has multiple classes of these type which can get probably really confusing especially for a library. I imagine myself having to pick between MyClass, MyClassV2, MyClassV3 etc.
In an ideal world, new versions would introduce additional functionality while still remaining 100% backwards compatibility with previous versions of the API. Unfortunately, the ideal world remains elusive, and it is not always possible to retain full backwards compatibility. A versioned suffix is the appropriate pattern in this case.
The standard .NET naming convention is to use incremental numbering, like Class, Class2, Class3, etc.. This comes from the naming convention for COM interfaces, designed for exactly the use case you're describing. For example, the IHTMLDocument interface currently has 8 versions, from IHTMLDocument up through IHTMLDocument8.
The original Framework Design Guidelines book, by Cwalina and Abrams, explicitly recommended this practice, with the authors having this to say:
DO use a numeric suffix to indicate a new version of the existing API, if the existing name of the API is the only name that makes sense (i.e., it is an industry standard), and adding any meaningful suffix (or changing the name) is not an appropriate option.
// old API
[Obsolete("This type is obsolete. Please use the new version of the same class, X509Certificate2."]
public class X509Certificate { ... }
// new API
public class X509Certificate2 { ... }
The old convention, followed by the original Windows team, was to add the suffix Ex to new-and-improved versions of an API, which comes from the word "extend." This doesn't scale well, however, leading to functions confusingly suffixed ExEx. I don't think there was an ExExEx; everyone was afraid to touch those APIs. The Framework Design Guidelines recommend explicitly against this practice, the folks who went on to architect .NET having learned their lesson:
DO NOT use the "Ex" (or similar) suffix for an identifier to distinguish it from an earlier version of the same API.
[Obsolete("This type is obsolete. ..."]
public class Car { ... }
// new API
public class CarEx { ... } // the wrong way
public class CarNew { ... } // the wrong way
public class Car2 { ... } // the right way
public class Automobile { ... } // the right way
Obviously, as their last code sample hints, if you are adding support for a specific feature in the new version of the API, you would be best off naming the new class/interface with a reference to that particular feature.
And although the above has focused almost exclusively on classes and interfaces, the same logic would hold true for any member functions of that class that might be added in later revisions. The original function could retain its original name, with the newly added function having a different name that either reflects its iteration or its added functionality.
I was wondering if there is a better way of naming these "versioned" classes.
There is no .NET naming convention for "classes which fix bugs in other classes". I would advise with other developers in your workplace and see if they have any company conventions for such a thing. I think consistency is of importance more than the actual name.
And on a side note to your problem, I wouldn't create a new class at all. I would mark the method with DeprecatedAttribute and implement the logic inside the same class, exposing a new set of API methods which are properly documented to state they are here as a fix. The clients of your library are probably already familiar with MyClass, and doing so would ease the use for them, interleaving them the need to ask themselves each time "which version of this should I use".
I would copy all the behaviour of your existing class to a new one, rename the original one to indicate that the class is obsolete, rename the new one to the actual name from before and mark the original one (with the new name now) as [Obsolete] indicating that it should not be used any more. Thus all consuming code automatically invokles the new behaviour. So your new class with the correct behaviour gets the name of the original class, where the buggy one gets a version-number for instance.
For legacy code you can do the opposite, make a new class with new name and mark the old one as Obsolete. I know SDKs with a version-number, where the last number indicates the most recent version of the class, and all the others have such an attribute together with a notice within the docs mentioning that the class is superseded with a new version.
For clarity, if that happens, I use ClassV2. That indicates that it's another version of the class.
I think duplication class name will seriously confuse other people overtime. You extract method with c# interface and implement different version.

What is Reflection property of a programming language?

Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.

How to handle same class name in different namespaces?

I am trying to create a common library structure. I am doing this by creating separate projects for every common lib I want.
I have the following 2 namespaces: MyCompany.ERP and MyCompany.Barcode
I need both of them to have a class named Utilities and be static. If I do that I will then need to specify the full namespace name before my static class in order to access it.
Is there any other preferred way to do it?
Or I should go for different names in classes like BarcodeUtils and ERPUtils?
If i do that i will then need to specify the full namespace name before my static class in order to access it?
No, there is no need for that, though the details depend on the class that will use these types and the using declarations it has.
If you only use one of the namespaces in the class, there is no ambiguity and you can go ahead and use the type.
If you use both of the namespaces, you will either have to fully qualify the usages, or use namespace/type aliases to disambiguate the types.
using ERPUtils = MyCompany.ERP.Utilities;
using BCUtils = MyCompany.Barcode.Utilities;
public void MyMethod()
{
var a = ERPUtils.Method();
var b = BCUtils.Method();
}
There isn't any other way. You can make an aliases in using directives:
using MC=MyCompany.ERP;
using MB=MyCompany.Barcode;
...
public void Test()
{
var a = MC.Utilities.Method();
var b = MB.Utilities.Method();
}
It's the simplest way to manage them.
The MS guidelines have the following to say:
Do not introduce generic type names such as Element, Node, Log, and Message. There is a very high probability it would lead to type name conflicts in common scenarios.
and
Do not give the same name to types in namespaces within a single application model.
I concur that it's probably a good idea to use BarcodeUtilities and ErpUtilities instead. (Unless the utility classes are not meant to be used by client code, in which case you could name them Utilities and make them internal.)
"Utilities" is not a very good name for a class, since it is far too generic. Therefore, I think you should rename both of them to something more informative.
You can use an alias:
using BarcodeUtils = MyCompany.Barcode.Utilities;
on the pages you have clashes. But ideally rename them if this is happening in a lot of places.
I would suggest using different class names. If you really want to call both of them Utilities then you could use the alias feature on the using directive, e.g.
using ERP = MyCompany.ERP;
using Barcode = MyCompany.Barcode;
...
ERP.Utilities.SomeMethod();
Barcode.Utilities.SomeMethod();
You will have to use the full path when both are named the same. Otherwise you will get an ambiguous reference error.
You can use an alias however that will save you some typing:
using Project = PC.MyCompany.Project;
I would go for a different name that's somewhat more descriptive. A
It actually depends on the purpose of your classes. If you are going to distribute your Barcode.Utilities and ERP.Utilies seperately it is better stay like this. On the other hand, if you are going to use them only in same class, you may use 2. method for easiness of code.

Should I use (otherwise optimal) class names that conflict with the .NET BCL's names?

This situation probably is not entirely uncommon to some of you: you have some functionality to put in a class but the perfect name (*) for that class is taken by one of the classes in the System namespace or other namespace/class that's not yours but you're using/importing.
(*) By perfect I mean small, concise and clear names.
For instance I have an Utils class that has a Diagnostics (mostly debug utils) class and a Drawing class. I could:
have a DrawingUtils class and a DiagnosticsUtils class, but that just smells like bad structure.
pick a thesaurus and be done with an worse, longer or awkward name that's casually still not taken.
Write class names in my native language instead of English.
Ask the smart guys at StackOverflow.
I think options 1-3 aren't promising :(
EDIT:
Since my chosen answer doesn't address the problem definitively (neither I do), what I'd recommend for people facing the same situation is to ask yourselves: Will you frequently use the conflicting BCL class/namespace? If no, then let your name conflict (as I did with Diagnostics). If yes, add a word that limits the possibilities of your class/namespace.
In practice, this means:
"Drawing": Something that draws.
"MyCustomControlDrawing": Something that draws only on MyCustomControl. e.g.: "WidgetDrawing".
EDIT2:
Another solution to take a look next time: Extension Methods (courtesy of Lawnmower).
I don't see any issue with keeping the names Drawing, Diagnostics etc. That's one of the purposes of namespaces, to resolve naming conflicts.
The beauty of namespaces is that they allow you to create classes with identical names. You can assign an alias to a namespace when you import it into your file with a using statement.
using MyAlias = My.Custom.Namespace;
this will keep your classes separate from Microsoft's.
you can then reference your classes as
MyAlias.Diagnostics
or you could alternatively assign an alias to Microsoft's namespace, but I wouldn't recommend this because it would confuse other developers.
To me, it really isn't worth the hassle of purposefully writing conflicting class names. You'll confuse other developers who aren't familiar with your codebase, because they will be expecting to use BCL classes but end up with yours instead (or vice versa). Then, you just waste their time when they have to write specific using aliases.
Honestly, coming up meaningful identifier names is a useful skill, but it isn't worth delaying your development. If you can't come up with something good quickly, settle for something mediocre and move on. There is little value in toiling over the names. I dare say there are more productive things you could be doing.
EDIT: I also don't believe that "small" is a component of a "perfect" identifier. Concise and clear, for sure, but if it takes a longer name to convey the purpose of a particular construct, so be it. We have intellisense, after all.
Use namespaces to disambiguate your classes from the classes in other namespaces. Either use fully qualified names or a using statement that tells the compile what you need:
using Type = MyReallyCoolCustomReflector.Type;
Now if you want to still use the Type class from the System namespace:
System.Type sysType = anObject.GetType();
Generally I try to avoid name duplicates but this doesn't always work out that way. I also like simple, readable and maintainable code. So as often it is a trade-off decision.
Well, if you want to avoid a namespace collision there are a couple of things you can do:
Don't collide, instead choose a unique name.
Example:
If you are creating a Math class you can name yours CamiloMartin.MathHelper
Use the long namespace to distinguish between collissions.
Example:
public class MyClass
{
public int SomeCalculation(int a, int b)
{
return MyNamespace.Math.SomeFunc(a, b);
}
}
Using an alias to differentiate.
Example:
using System.Math;
using SuperMath = MyNamespace.Math;
namespace MyNamespace
{
public class MyClass
{
public int SomeCalc(int a, int b)
{
int result = Math.abs(a);
result = SuperMath::SomeFunc(a, b);
return result;
}
}
}
Just for the record: .NET framework doesn't have neither Utils nor Diagnostics class. (But does have System.Diagnostics namespace.)
Personally I don't like general-purpose classes like Utils because their methods are not very discoverable (and usually either too general or too specific), therefore I would justify their use only as for internal classes.
As for the rest -- I agree with others on that namespaces are convenient. (Although I would thought twice to name the class if there is already a class in System with the same name, not because of name conflicts, but rather because the reason why I can't use 'original' class could mean that the class I'm about to create is semantically different.)
Often its possible to choose a more specific name. Take Utils for example. Absolutely everything can be called a utilitiy. For the reader of your code this classname is worthless.
Often utility classes are a collection of methods that didn't really fit anywhere else. Try to place them where they belong, or group them by some criteria, then use the group as a classname. Such grouping is in my experience always possible.
In general:
That's what we are doing (hey, we can refactor it later)
Used it once or twice but only on important classes. Especially useful if you don't know the 'perfect' name yet.
don't even think about this...
Using namespace aliases is no fun. So I avoid it if I can.

What should I name my files with generic class definitions?

I'm writing a couple of classes that all have generic type arguments, but I need to overload the classes because I need a different number of arguments in different scenarios. Basically, I have
public class MyGenericClass<T> { ... }
public class MyGenericClass<T, K> { ... }
public class MyGenericClass<T, K, L> { ... }
// it could go on forever, but it won't...
I want them all in the same namespace, but in one source file per class. What should I name the files? Is there a best practice?
I've seen people use
MyGenericClass`1, MyGenericClass`2 or MyGenericClass`3
(the number is the number of Generic Parameters).
I think that's what you get as a TypeName when you call .ToString on the class.
When this situation arises I adopt the same convention that is used in the XML documentation comments for C# generics, which is to use { and } instead of < and > because angle brackets aren't friendly in either XML or file names but curly ones are. So something like:
MyClass{T}.cs
MyClass{T,K}.cs
If you really have very many parameters though, this can get somewhat unwieldy as a naming scheme, so then I'd tend to adopt the CLR convention of backtick followed by parameter count, e.g.
MyClass`1.cs
MyClass`2.cs
Or mix and match the two schemes as fits the situation.
I think you won't find much dogma in the C# community favoring separate files for each variant of a generic class with the same name; I prefer to just use one for the case you're describing, though I could see a case for what you're proposing if the code is necessarily complex/long for each variation. Generally I'd just use the name of the class in question as the filename.
If I were going to separate the variants into separate files, I could see using Michael's solution, though that would be a bit painful for those of us who use Unix-style tools on the command line in, for example, Cygwin or AndLinux. I'd probably use an underscore or no punctuation. Or something like 1P, 2P, 3P as the suffix.
I'd put them all in the same file unless they are large (which usually they won't be, except the one with the most Ts).
There isn't really a best practice for naming classes besides what you find in the .NET framework guidelines, as it's part of the creative side of programming, and unfortunately the SSCLI only goes back to 2.0 so you can't find much help there.
I usually use Classname.1.cs, Classname.2.cs, etc... where the number is the number of generic arguments, similar to the ``1notation used in the framework documentation (and in XML documentation in your sourcecode). Sometimes you also have a class with no generic arguments (similar toICollectionandICollection` in the framework), and the filename would be just the class name, as expected.
In contrast to using a backtick, this has the advantage that you won't have any invalid characters in the filename. Not all filesystems, versioning systems, operating systems allow a backtick character in the name.

Categories