What should I name my files with generic class definitions? - c#

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.

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.

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;

Why to use extension methods if source code is available instead of inheritance [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I just read in msdn/books that extension methods are useful to add methods to existing classes if the existing class source code is not available , however I have noticed in some very good written open source codes that extension methods are still used along with with inheritance (abstract, interface) on classes that have source code written by the author himself/herself.
This is just general question , no source code here.
A common reason is dependency management: Let's say you have a fairly general class User and a not-so-general class GravatarImage. Now it might make sense to be able to call SomeUser.GravatarImage() instead of GravatarImage.ImageForUser(SomeUser). This is not only convenience; in a large project, it might be hard for other programmers to find out the 'right' way to do something. IntelliSense will help a lot here.
However, the User class is a "backend" class and should not need to know anything about images, views, gravatars or URLs, so you want to keep dependencies clean.
A similar argument applies to LINQ, which basically consists of extension methods. These extension methods, extend the collection interfaces, so you can create a lot of functionality with very small interfaces. Implementing a new kind of IEnumerable is very easy, yet you gain all the functionality that is provided by LINQ.
The IEnumerable interface, to stick to the example, doesn't allow much more than getting an enumerator. Instead of asking each implementor to provide a Count method, you can call the extension method which will accomplish the same.
It is noteworthy, however, that a method like IEnumerable.Count() can be very slow (it has to touch every element), whereas a direct implementation of the underlying class could be as simple as returning a simple int.
A lot of the answers already here are great: I love using extensions for optional behavior, and on interfaces. There are a couple of other good reasons.
Avoiding abstract method overloads. Consider the following interface:
public interface IUserService
{
User GetUser(int userId);
User GetUser(int userId, bool includeProfilePic);
}
We can see how it might be useful to optionally include the profile pic when getting a user from a IUserService. But, with both methods on the interface, they could be implemented in totally different ways (something this simple probably wouldn't, but I run across this problem a lot). Using extension methods, overloads cannot have divergent behavior:
public interface IUserService
{
User GetUser(int userId, bool includeProfilePic);
}
public static class UserServiceExtensions
{
public static User GetUser(this IUserService userService, int userId)
{
return userService.GetUser(userId, false);
}
}
Respect encapsulation. If you have a bit of additional functionality that you want to put on a class, but it does not need any access to internal members of the class to function, and holds no state, then using an extension method is desirable. The fewer things that know about a classes internal members and state the less coupling you will have, and the easier it will be to maintain code in the long run.
A downside: you can't Moq Extension Methods
A lot of times this doesn't matter. It means that, in order to mock out behavior behind an extension method, you usually need to know how the extension method works, and mock the virtual methods it calls. This couples your tests to an implementation of the extension method. This is just annoying if your extension method is simple and unlikely to ever change. This is pretty bad if your extension method encapsulates some complex set of calls. For that reason, I usually only use extension methods for relatively simple behaviors.
In C#, providing extension methods for an interface is usually an attempt at approximating* mixins.
A mixin can also be viewed as an interface with implemented methods.
Although C# does not support mixins, providing extension methods to an interface class that others can implement is a nice way of "bolting on" functionality.
Here's a real-world example of a simple interface with bolted on functionality delivered as a mixin:
public interface IRandomNumberGenerator
{
Int32 NextInt();
}
public static class RandomNumberGeneratorExtensions
{
public static Double NextDouble(this IRandomNumberGenerator instance)
{
return (Double)Int32.MaxValue / (Double)instance.NextInt();
}
}
// Now any class which implements IRandomNumberGenerator will get the NextDouble() method for free...
* The big difference between C#'s approximation of mixins and the real thing is that in supported languages mixins can contain private state, where as extension methods on interfaces in C# can obviously only access public state.
A good way to think of extension methods is like a plugin-type architecture - they give you the ability to include/exclude functionality for a particular type instance. To answer your question specifically:
Why to use extension methods if source code is available instead of inheritance
The simplest answer to that would be for optional functionality. The most common, and probably the most important, reason for using extension methods is being able to extend a particular type without changing any core functionality. Deriving new types for the sake of adding a couple of methods is overkill, even if you had control over the source it would make more sense to make the type partial instead. Extension methods tend to be used to solve problems for particular scenarios and don't really merit going into the core code base. However, should you find yourself using them all over the place then that's a good indicator that your probably not using them correctly.
For example, consider the following extension:
var epochTime = DateTime.UtcNow.ToEpochTime();
ToEpochTime would return me the date time as Unix Time. This would be useful as an alternative way of generating a timestamp or serializing the date. However, it's quite a specific function so it wouldn't make sense being part of DateTime but by making it an extension method it allows me to simply include this type of functionality if & when required.
There are a couple of disadvantages I can think of with subclassing as an alternative to extension methods:
It can be excessive if you only want to add a couple of lightweight methods.
It can create problems if you already have a complex inheritance structure (especially if your class already has subclasses), or intend to have one in future.
I often use extension methods for bridging boundaries between namespaces in a way that increases readability and maintains separation of concerns. For example myObject.GetDatabaseEntity() reads quite nicely, but the code for GetDatabaseEntity() should be in the database section of the code, not in my business logic. By putting this code in an extension method I can keep everything where it belongs without adding the complexity of subclassing.
Additionally, if myObject was instantiated in my business logic before being passed to the database code, then the business logic would need to include the database namespace. I prefer to have each module's responsibilities clearly demarcated, and would prefer my business logic to know as little as possible about the database.
There are also a couple of tricks that extension methods are useful for (some of which have been mentioned already in other answers):
They can be applied to interfaces (LINQ uses this a lot).
They can be applied to enums.
They can be used as event handlers if you create them with the correct signature. (Not that I'd recommend doing this as it can lead to confusion, but it can save you from storing references to objects that you would otherwise need to stick in a collection somewhere - watch out for leaks!)
This may be a somewhat specialized case, but I've found extension methods useful when providing "rules" of various types to existing classes.
Say you have a classe SomeDataContainer, with lots of members and data, and you want to export certain pieces of that data in some cases, and other pieces in other cases.
You could do something like this in SomeDataContainer:
if(ShouldIncludeDataXyz()){
exportXyz();
}
(...)
private bool ShouldIncludeDataXyz(){
// rules here
}
private void ExportXyz(){ (...) }
... but I've found that this sometimes gets messy, especially if you have lots of classes, and many rules, etc.
What I've done in some cases, is to place the rules in separate classes, with one "rule class" for each "data class", and create the rules as extention classes.
This just gives me a hierarchy of rules in one place, separated from the core data - a separation I find useful anyway.
The resulting code would still be similar to the above:
// This now calls an extention method, which can be found
// in eg. "SomeDataContainerRules.cs", along with other similar
// "rules"-classes:
if(this.ShouldIncludeDataXyz()){
exportXyz();
}

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.

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