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

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.

Related

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

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;

What hack can I use to define a C# property with same name as class?

I'm using C# to make a .Net class library (a DLL) that will be distributed widely. I have an abstract class called Value, and I want it to have an abstract double property that is also called Value i.e.
public abstract class Value {
// Only accessible by subclasses within the project.
internal Value() {}
public abstract double Value {
get;
}
}
But the C# compiler won't allow this - I get the message "member names cannot be the same as their enclosing type", as discussed here.
I understand that the easiest thing to do would be to change the name of the property or the name of the class... But really I want the names to be like that, and I'm quite happy to implement an ugly hack to get it that way. So long as it works properly from external code that uses this DLL.
Unlike C#, VB.Net will allow me to define a property with the same name as the class, so I'm currently investigating merging my C# project with a VB project that defines the Value class (and its Value property) to make one DLL. This doesn't seem to be quite as straightforward as I was hoping.
Another option would be to re-write the whole project in VB... Not very appealing, but I'll consider it if necessary. I prefer C# over VB.Net but my priority is to get the built DLL the way I want it.
I'm wondering what other alternatives there might be. Any ideas for a good way to hack this?
EDIT: From the comments below it's clear that quite a number of people don't think much of the name "Value" for a class... Could anyone explain why it's so bad? I know it's not very descriptive, but I think it fits well in the context of my project. Is it because it's a keyword in C# that's used in property setters?
You cannot do that directly. You could, however, consider:
impelenting an interface with a Value member, and using explicit interface implementation (callers would have the use the interface, though)
renaming it in the class, and using an extension method to expose a Value() method, so obj.Value() works
rename it in the class, but expose it as Value in the subclasses
Ugly hack:
public abstract class ValueBase {
public abstract double Value { get; }
internal ValueBase() {}
}
public abstract class Value : ValueBase {
internal Value() {}
}
public sealed class ValueReal : Value {
public override double Value { get { return 123; } }
}
If your class is representative of a double (except for some additional metadata), you could opt for a conversion operator:
public abstract class Value
{
protected abstract double GetValue();
public static explicit operator double (Value value)
{
return value.GetValue();
}
}
Then your client code could access the metadata or cast an instance of type Value to a double. Depending on the metadata and usage, you might make the conversion implicit so you don't have to do an explicit cast, and you might define a conversion from double to Value.
There is a similar approach used by the System.Xml.Linq assembly where, for example, XElement can be cast to any primitive type as a means of accessing its "value".
As other people have said, this is not possible in C#.
Other people have criticised the name Value as a class, and while I agree it's likely too generic, I can see situations where it may make sense.
Bearing that in mind, if Value is an abstract class, perhaps ValueBase might be a decent, conformant, name? Much of the .Net framework (particularly WPF) uses XxxBase.
Another option to consider is prefixing the class name with the name of your project, as in FooValue.
Value is a terrible name for a class. It's extremely vague, so it does nothing to describe what a Value represents, and it clashes with the reserved word 'value'. You will find yourself using value = Value.Value, wondering why your code makes no sense, and eventually trying to fix a hideous bug that is a direct result of using 'value' instead of Value or value or _value or this.value. And what happens when you have to store another kind of arbitrary number? Will you call it Value2?
Name the class with a more specific and meaningful name and the problem will no longer exist. Don't fix the symptoms - fix the cause.
Even if you only rename it to "DataValue" or 'MySystemValue', you will be doing yourself a great service.
Bowing to popular opinion, I've decided to rename my Value class to DataValue. I'm pretty happy with that name, and it means I don't need any hacks to have the property called Value. So thank you very much to everyone for the feedback.
But, despite the useful answers, I still don't think the question has been answered ideally. None of the proposed solutions do exactly what was asked for, or at least not without side effects like the requirement for an otherwise-superfluous interface or public class. I should probably have been clearer in my question that I was perfectly happy to consider a hack that involved unsafe code, or modification of intermediate language or some such, as my priority was to get the public API of the DLL the way I wanted it, irrespective of whatever messy hacks might lurk hidden within it's source.
So here's the best solution that I could come up with. I haven't actually done it myself (no need now I'm using a different name for the class), but I don't have any reason to suspect that it won't work:
In the solution that contains your C# class-library project, add a new VB class-library project.
In the VB project, create the class (Value in my original example). In VB you'll have no problems adding a property with the same name as the class.
If your VB class has internal methods that need to be referenced by your C# code, reference the C# assembly using InternalsVisibleTo in your VB class.
You should now be able to reference your VB class from your C# project. But when you build the solution you'll get two separate DLLs: one for the C# code and one for the VB code. It looks like the ILMerge tool makes it very straightforward to merge the two DLLs into one (just one call from the command line).
So finally you should have a single DLL that contains the class with the property of the same name, and all the code in your C# project. Other projects that use that DLL (C#, VB, or any other .Net language) should not see your hacky effort - all they'll see is a coherent API with no superfluous public classes or interfaces.

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.

Are there any plans for "extension properties" in a future version of C#?

I've thought of this before and it came to mind again when reading this question.
Are there any plans for "extension properties" in a future version of C#?
It seems to me they might be pretty stright-forward to implement with a little more "compiler magic". For example, using get_ and set_ prefixes on extension method names would turn that method into an extension property:
public class Foo
{
public string Text { get; set; }
}
public static class FooExtensions
{
public static string get_Name(this Foo foo)
{
return foo.Text;
}
public static void set_Name(this Foo foo, string value)
{
foo.Text = value;
}
}
Are there any technical restrictions which would prevent this? Would this create too much stuff going on behind the scenes? Not important enough to be worth the effort?
The official site for feature requests is http://connect.microsoft.com/VisualStudio.
There has already been a request for extension properties here.
Microsoft's answer on 7/29/2008 included the following:
Extension properties are a common
request, and we actually got quite far
with a design for the next version of
the language, but ultimately had to
scrap it because of various
difficulties. It is still on our
radar.
Generally I think this would encourage poor practice.
Properties are supposed to represent some kind of state about the object in question, whereas methods should represent units of work. But many developers tend to put computationally intensive or relatively long-running code in the getters and setters where they would be much more appropriate as methods.
Extending an object is not the same as deriving from it. If you need to add properties, from a philosophical perspective you're talking about needing to add stateful information to the object. That should be done by deriving from the class.
Although I don't think what you're proposing is a good idea, you can get pretty much the same thing with the upcoming dynamic type in C# 4. Part of what is planned is to allow new properties and methods to be added at runtime to existing objects and types. One difference is that you won't have the compile-time checking of an extension property.
There might be something to be said about that kind of trick.
Just look at Attached properties in WPF. They do give tremendous power for declarative behavior attachment. But I'm not sure what that would look like outside of a declarative context...
I'm not sure how that would work. Extensions have to be static, so the property itself would have to static. The means whatever you use to back these properties would also be static. But expect your planned use for these expects them to be associated with the instances indicated by the this keyword rather than the type itself.
"Extension properties" are available today via inheritance. Adding such a beast would encourage poor oop practices and generaly be more trouble than its worth.

Categories