StyleCop SA1402 and Generics - c#

I think SA1402 is a great rule but I have problem with generics. I've got a class that uses the Func delegate, so the names roughly parallel that signature. That is, I have classes named Operation<TType>, Operation<T, TType>, Operation<T1, T2, TType> and so on. According to SA1402, I need to put all these small classes in separate files and come up with some strange decoration for the file name. Additionally, if I need to change one of these items I'll typically need to make changes to the rest. This seems less supportable than a single module.
Does it make sense for SA1402 to allow generics of the same basic class (as well as partials) to reside in one file? In this case all permutations of the class Operation would reside in 'Operation.cs'.

They are several nameing convension. It seems the most popular is
Operation[TType].cs
Operation[T,TType].cs
Operation[T1, T2, TType].cs
But you can also use something more classic, like
Operation`1.cs
Operation`2.cs
Operation`3.cs
(see Convention for Filenames of Generic Classes)

I tend to agree with you, in general, SA1402 is a good idea. But in this specific case, and others like it (i have a generic and non-generic implementation of the same class). Like many others I think having more than one class per file is totally fine if it makes sense. I choose to ignore this warning at a very specific Scope and Target level:
[assembly: SuppressMessage(
"StyleCop.CSharp.MaintainabilityRules",
"SA1402:FileMayOnlyContainASingleType",
Justification = "How else would we name generic and non generic (https://stackoverflow.com/a/4063061/516433).",
Scope = "type",
Target = "~T:Pastdev.Cli.AppResources`1<!!0>")]

Using the Operation<TType>.cs approach will work if you have overridden the StyleCop's fileNamingConvention setting (File naming conventions).
Otherwise, it works automatically if you name your file like: Operation{TType}.cs, etc. (Note the curly braces)

Related

When should extension methods be avoided?

Before you start pointing me to duplicates just know that I have read nearly all the posts on SO about extension methods. I am just trying to play devil's advocate for a minute to consider the alternative to my working opinion.
Recently I was working on a project and a need came up for a method to be a base of an interface. So I suggested we write an extension method and it was shot down. Saying it added complexity and harder to debug.
I of course argued and got on SO to find all the wonderful posts that show the many reasons why to use extension methods. Not to forget that a lot of the .net framework uses them. We eventually did not use it as I was overruled by the team.
But then it got me thinking, are there times when an extension method could be used but shouldn't be?
I really couldn't think of any but thought I would post here and see if anyone could think of any other reasons why they shouldn't be used.
Any time you have a function which is "generally applicable" to an object of a certain type, regardless of its state, an extension method is a good choice.
For example, today I added two new extension methods to our codebase:
public static XElement ToXElement(this XmlElement element) { }
public static XmlElement ToXmlElement(this XElement element) { }
Both of these are, generally speaking, valid on the types they extend regardless of the state of the instance or where we are using it.
If your method does not meet that criteria, it should probably be moved to a helper method closer to the context where the particular case is always true or easily checked.
For example, a developer recently nominated this to be an extension method:
public static bool ParseYesNoBool(this string input) { }
There are two problems here: first, this will appear on all strings in the application, even though the number of strings which might ever be candidates for this case are very small. So we've broken the first rule, in that it is not useful regardless of state. Similarly, but second, the consumer of this functionality is limited to a single parser for one particular connector to an external system. So promoting implementation-specific functionality into the general-use namespace makes no sense. This was downgraded to a helper method in the parser.
As far as readability and debugging, that is just incorrect for a developer of any reasonable skill level.
In general if you control the source-code for the assembly and adding the method does not cause any breaking changes to existing code (which would have been the case if for example LINQ had not been implemented via extension methods) it is better to just add a normal method.
This discussion of the Framework Design Guildelines section on extension methods contains some good advice. I think the relevant portion for your scenario is:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface.
If your proposed usage did not pass that test then it should have been shot down.
I would say you should avoid them when "they do not make the intend of the code more clear". Of course, whether or not some code (or codeing style) is "more clear" varying widely between people, so that's pretty much useless. (I had one boss who said we shoudl avoid using interfaces because they made the code "too complex and hard to understand")
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Any time you break the intent and design for the feature I would recommend reconsidering the use of an extension method. I see a few situations when you don't want to use an Extension method:
1) Changing the Object Model to allow for an Extension method: The class you want to create an extension on is an abstract class. This is going to require you either make each inherited class it's own version of the extension or remove abstract from the class. Either way, you are changing the object model in order to use an extension method.
2) Forgetting the Decorator Pattern: The number of extension methods you create for a class exceeds three. I find it is easier to organize/communicate and maintain the domain/object model with decorated objects than with extended objects. However, the opposite is also true: If a decorated object has less than four methods, I find a lot of almost "empty" objects in my project.
3) Private functions: Private functions are meant to modify(create, delete, etc..) the object and extension methods are meant to use the type, much like a struct would. If you find the extension is being assigned to another instance of the type then it probably should not be in an extension.

What is the correct file name for the interface "IRepository<T>"

Just curious what people would name the file that contains the generic interface IRepository<T>.
IRepositoryT.cs?
Update
One minor point to add. Normally, when you change the name of a class file, Visual Studio asks if you want to do a rename on the class as well. In the case of IRepository<T>, no matter what I name the file (IRepository or IRepositoryT or IRepositoryOfT, etc.), the link between the file name and the class name is never established.
Personally I would use IRepository.cs. The only difference is when I, for a generic class, also has a nongeneric version of the same, either for compatibility with legacy code, or to provide static methods available to any T.
In this case I would name them:
IRepository.NonGeneric.cs
IRepository.cs
I would name it as I say it: IRepositoryOfT.cs
I usually just use IRepository.cs. And unless they are very big classes, I tend to keep IRepository and IRepository<T> in the same file. Usually with the non-generic on top, since the generic one usually extends the non-generic one.
When I have split it into two files, I have usually used IRepository(Of T).cs, but the suggestion from others here with IRepositoryOfT.cs sure is a good one. Might use that one :p
I would go with IRepository.cs
I don't think the fact that the type is generic should make a difference.
Maybe this is helpful.
Depends if you have IRepository also, and you like to keep different interface definitions in different files.
If so, IRepositoryT.cs, or else IRepository.cs
And I'd put it in a folder named Interfaces, but that's me, and I'm a bit OCD in this area

Refactoring: Nested class or separate classes?

I'm currently doing some refactoring (+ adding new features) to some of our framework classes. The situation is that we have a single (god-like) class which does a bunch of logic we'd like to split up. The class represents something like a validation rule for fiscal codes. So it does validation of the names of the person, birthdate etc..
What I am going to do is to split it up in single rules, basically a rule which validates the person's firstname against the fiscal code, another one for the birthdate and so on. For the programmer at the end it looks nearly the same. Instead of invoking the huge constructor of the FiscalCode rule, he'll do something like FiscalCode.GetRules(...) and pass the parameters here. The GetRules(...) will then internally construct the single rules and pass them back as an array. That's perfectly fine and correct for us.
So much for your background. Now my question is the following. The FiscalCode class (which is our current mighty god-class) has a lot of utility methods which will be needed by more of the single "rule classes" I'm going to create. What I know is that I will somehow still need the FiscalCode class, for doing the GetRules(...) thing (this is to remain constant somehow for the programmers, not that they have to do a completely new thing).
I have two options which come to my mind:
Create my new rule classes and access the public static utility methods of the FiscalCode class
Create my new rule classes as inner nested classes of the FiscalCode class s.t. I have already access the utility methods (and therefore no need for exposing my utility methods)
I have already a favorite, but I'd like to hear the opinion of some of you first.
Thx
As your methods became 'utility methods' you need to make them static and public, but probably you need to rename your FiscalCode to FiscalCodeUtil. So it will be obvious what kind of methods it contains.
I would also suggest a review of the Specification Pattern, which gives some direction on how to approach this type of problem. This post also gives some examples in C#.
The suggested Specification Pattern would steer you towards your option #1.
What dependencies do these utility methods have on the FiscalCode class or the rule classes? Is there state kept by them?
If there aren't any dependencies I'd suggest moving those utility methods to a seperate class, and have the FiscalCode class or rule class call into those methods as appropriate.
For the options you give, the only difference between 1) and 2) is whether the rule classes are visible to classes that don't use them. I don't think thats really an important objective. I used to worry about that all the time when I did c++... it was a waste of time.
IMO you should go for the first option because that way, you can expose the newly created classes to outside world, and can write code that is reusable elsewhere as well. If you go with the second option, you are creating very specialized classes. Your outside code may not even know of its existence, but that might be good for encasulation. Still, at some point you may decide to use the specialized rules outside the scope of your larger class, and for that scenario, you are better served with the first option. What is your pick though?
If the class will not be used outside the FiscalCode class, then make it nested. The important thing is to pull the responsibility of this new class out of FiscalCode; where it resides then becomes a mere question of choice. When the new class gets more dependents, you could make it an outer class.
I would go with it like this (I'm not that good at OOP so take it with a grain of salt):
Rule classes (nested in FiscalCode) implement an IRule interface exposing rule methods (like Validate(), with whatever return type floats your boat). FiscalCode
has an AddRule() method which manages an internal collection of rules and returns a reference to self in order to permit method chaining:
FiscalCode fc = new FiscalCode();
fc.AddRule(new RuleClass1(<params specific to RuleClass1>)
.AddRule(new RuleClass2(<params specific to RuleClass2>)
...
Also, FiscalCode has a Validate() method which iterates through each rule's Validate() and manages errors.
IMO this is quite handy to use and still permits to nested rule classes access FiscalCode's utility methods.

How to avoid having the same name for a class and it's namespace, such as Technology.Technology?

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...
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.
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.
One general cop-out is to name your namespace "Entities" or something.
Another cope out, just call the namespace after the name of the company you are working for.
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... :)

What is a good (natural-language) naming scheme for belonging or property interfaces

NOTE: This is not the popular interface naming question about
using or not using "I" at the beginning.
I encounter often the problem to name
an interface, which indicates a belonging or property of a class.
(Please see following list)
Let's brainstorm, what kinds of interfaces are there?
Indicate the "kind" of a class
DataStructure, Number, Thing
Indicate the "profession" of a class
Comparator, Executor, Listener
Indicate a possible action performed with a class
Comparable, Executable, Closeable
The above are all clear to anyone, but let's get to my problem:
Indicate a belonging or property of a class
HasListener, LinksToRoot, BelongsToParent, KnowsSibling, ContainsChildren,
Named, WithDescription, ...?
So, the last point is my problem. My english is not perfect,
but even I feel strange about such names.
They sound to me less successfully chosen then other, less meaningful.
But I often end up choosing right this kind of names.
It is even a greater discomfort in C# where interfaces are expected
to start with an 'I':
IHasListener, IKnowsSibling, ...
Sound to me like LOLSPEAK "I can haz a kitteh, tawtally being full of
cuteness, OMG!##!"
So, how should I name an interface which indicates a belonging or
property of a class?
The problem is the way you choose to describe the "belonging of a property".
Most of your examples you gave can be mapped to the other categories you mentioned.
Just a few, for example:
HasListener => implements Listenable
ContainsChildren => implements Parent
WithDescription => implements Descriptable
Try to stick with more conventional naming schemes, preferably ones that describe your object in the best, more readable manner.
Also, make sure you are not over-interfacing your classes with useless interfaces. Make it very concise and to-the-point, otherwise you'll developers reading your code will get lost very fast.
In some of the problem cases that you outline, I think there may be an answer by looking "from the other side":
HasListener -> Speaker
LinksToRoot, HasParent -> Child (or perhaps Node)
ContainsChildren -> Parent
Of course, different cases will be more or less obvious.
I think you can take some of what you're doing and turn them into "profession"-type interfaces:
HasListener -> ListenerContainer
WithDescription -> DescriptionContainer (Describable might also work, depending on what exactly a "description" is in this context)
A lot of your other interfaces seem to have something to do with a tree structure. I would suggest naming them according to their function in the tree.
ContainsChildren -> Parent or Collection
BelongsToParent -> Child
As for the other ones, I'd need to know more about what specifically these interfaces are for. Some of them, like Named, are probably named just fine.
Those sounds like terrible interface names to me, I agree. The "HasListener" sounds more like a method call that should return a boolean than an interface name.
Interfaces should not exist to hold/store properties of a class. They should be used to outline a relationship that all classes that implement it should follow. I personally stick with the "is a" relationship. If there is a direct relationship, i.e. a cat "is a(n)" animal, then I will create an interface for it and name it Animal giving it a reasonable name.
I would be really interested in knowing what the "HasListener" interface outlines. What exactly does it do? Why can't it be named MyProjectListeners(replacing MyProject with the project name) that describes what listeners defined for this project must adhere to?
HasListener is ok, as well as Listenable. I don't have anything against those.
But IHasListener is terrible: first because we don't really need the I prefix to tell that it is an interface (look at the class signature!) and second because it sounds like "I doesn't speak English".
The only interface in Java that I created with the I prefix was IRule. :)
I actually quite like the "IHasListener" approach.
In the .NET Framework, you'll find this in interfaces such as:
IRaiseListChangedEvents
IHasXmlNode
Names like "Listenable" suggest that the implementation does the listening, not that it contains a listener. IHasListener clearly says what it does.

Categories

Resources