While I think I understand why inline XML documentation (i.e. using three slashes - ///) isn't working for me, I'd like to get some guidance on how to work around my "problem".
I have an interface, and two derived classes. One derived class is for simulation, and the other is for talking to real hardware.
It's very likely that the hardware implementation would do something special that the simulator doesn't need to do. I have XML documentation for the hardware methods, and not for the simulator. However, when I hover over the method name, I don't get documentation in the tooltip at all, presumably because the XML docs aren't associated with the interface.
This certainly makes sense, and I plan to just put my documentation in the interface instead and live with it. I am still curious, though... how does everyone else do this? Is there some magical way to make the tooltip aggregate all of the valid XML docs? In other words, since the compiler doesn't know which derived class is being used, is there a way for it to show XML docs for all classes that implement this interface?
This won't solve all your problems but GhostDoc can quickly insert documentation into a derived class using the base class documentation. It's worth taking a look anyway if you're doing XML documentation.
Since you are programming to an interface, there is not a way to pass through the XML documentation from the implementation. The separation means that the two "sides" don't know about each other. Like you said, you could have two different implementations of that interface. In that case, you would have a conflict. That isn't a big deal for two, but what about 200? Besides, the point of using an interface is that you don't care how it is implemented. You know that when you call use an interface, the implementation will follow the contract. Use the XML comments on the interface to describe the contract, not the implementation of the contract.
I can feel your pain on this one and I'm not sure that there is a better solution.
Related
We are debating at work the best way to define methods for an entity class - as extensions methods or using partial classes. The kind of methods we're talking about don't modify the state of the entity, they are purely "helper" methods that interrogate the state and return a value.
The main benefit to both approaches is to keep the entity class clean, while still providing intellisense support to client code.
I don't have a strong preference either way but am curious to know if others have a preference (or know of documented guidelines) towards one or the other.
I started writing the list of merits for each approach that I could think of, but in the end all I've come up with is:
Partial Classes
The method definition resides within the class (even if it's another file) so Visual Studio tool support for "find method" (e.g. ALT-\ in resharper) will locate the method
The existence of the other file containing helper methods is obvious as soon as the entity class is opened due to use of the partial keyword
Extension Methods
The naming of the file ("entityNameExtension") and its whereabouts in the project (in an "Extensions" sub-folder) are intuitive and easy to search for
Can anyone else add their opinion to this?
PS I don't feel this is a duplicate of the following question, as the asker of that question was content to mark a response which outlined the functional differences as the correct answer, which doesn't answer the question about which approach is best practice in this scenario:
Partial Class vs Extension Method
EDIT - I'm seeking people's preference towards one approach or the other, as there are no documented guidelines that we can find for this particular scenario. Both approaches are possible and neither violates any design principles, so it is a matter of preference and I'd like to know yours.
In my opinion, extension methods are good for two things. First, when you apply them to interfaces, it gives you the illusion of writing an abstract base class that lets you define some common methods, but it's more flexible because a class can only have one base class but can implement multiple interfaces. Second, if you apply it to regular classes, then I tend to look at it as some kind of hacking. When the original class lacks some methods, and you really feel like they should have those methods, but they don't, and they are out of your reach, so you are forced to implement them somewhere else, as utility methods, and it gives you an illusion that it's actually there.
Both cases are syntactic sugar only in the end, but extending interfaces makes much more sense to me, if I just look at LINQ's Enumerable class for example. I've used those extension methods on dozens of completely different classes, so it really paid off. An example of a class extension method is when I made my own string.IsNullOrWhitespace before it was added to the framework.
Extending an interface seems right because the interface defines a contract, and you can rely on that contract in your extension method, but when you extend a regular class, it may change and break your extension method. Of course, interfaces may change, too, but they tend to be more thoroughly designed I think, but I don't have any statistics.
Then there's the case of object-oriented programming. Where do you feel like your method should go, who uses those additional methods, where are the boundaries. If you think a method belongs inside a class, then put it in the class. It makes sense, it's simple. People wrote really good classes before extension methods were invented, they put everything where it belonged and life was good, haha.
Partial classes are cool because they are not that big of a hack as extension methods. They are not syntactic sugar, not magic. It is merely the best and easiest way to deal with auto-generated classes, so I don't think too much of it. I've written some code generators, and they emit regions where humans can write their own stuff and it is not overwritten in subsequent code generations. It is more comfortable that way, but that's all. I can't change how .NET tools generate code, and they don't do it this way, so partial classes are the next best thing.
To sum it up, my opinion is to only use extension methods when you really have to, and go with partial classes whenever possible.
I dont know why you would create a partial class uless your original class has grown out of its purpose. Take a look at your classes you would like to extend, are they really doing one thing, or are they doing many things. Take a look at at the Single Responsibility Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle).
If you can create methods that OTHER CLASSES can take advantage of, I would recommend creating an extension class. It will extend the capability of other classes, making your toolbox more flexible.
I love design patterns, the problem is that some can be really tedious to implement.
For example, decorating an object that has 20+ members is just plain annoying.
So, I wanted to create a nice library of design patterns to be applied to classes (either as base classes or attributes) to make implementation of these patterns much quicker and eaiser.
The problem is...I'm not quite sure where to start - because I am mostly unfamiliar with attributes and reflection.
I would like to utilize attributes to mark Singletons (similar to the Export tag), Multitons, and Decorators...if at all possible. But I don't even know where to start in order to create a singleton attribute that alters the functionality of its instances.
My limited research has led me to believe that using reflection/late binding through an attribute and gaining access to all marked classes in the assembly, would allow you to hack together a singleton...but I'm still not entirely sure how that would be done.
A framework I found, called Ninject 1.0, created a Singleton attribute - but the library is so extensive and undocumented, that I am currently unable to follow its logic.
I feel like a library with this sort of functionality would be a great contribution to many developers out there. So, it would be greatly appreciated if someone could provide some sample code that gets me pointed in the right direction to create one of these patterns as an attribute - whose code isn't overly involved. Or if someone would be willing to walk me through Ninject's singleton attribute implementation so I may work off of that...
Thank you for your time and consideration.
I think you have a slight confusion on what design patterns mean.
A pattern is really a common way of doing things, designed to solve a particular problem.
You don't really use patterns for patterns' sake. More patterns usage doesn't automatically means good. You use a pattern to solve a type problem -- and hopefully that pattern is the recognized best-practice way to solve that problem. Don't try to appy a pattern to your code because you can.
Now, after all this, it can really be seen that what you are planning to do is not the right way of going about implementing pattern(s). You don't mark code with attributes etc. and then call them patterns. The pattern is your code. Your code is the pattern. For example, you don't mark a publisher/subscriber pattern on a class unless it really implements publish/subscribe functionalities. For example, you don't mark a class with "Singleton" and then it becomes a singleton pattern; using the Singleton pattern requires you to code your program (and your classes) around that design.
You may, however, mark code or classes with certain attributes that can aid in checking whether the code/classes conform to a particular pattern.
For example, you may implement a type checker that goes through all your class, check if anything is marked "publisher" and see if that class implements the "IPublisher" interface. Or your type checker can check if any class is marked "Singleton" whether the constructor allows construction of more than one instance at any one time.
But attributes and reflection is typically not the tools to implement a pattern.
In C#, where there is no multiple inheritance, the way you implement patterns is sometimes through the base class only. For example, you may implement a "singleton" pattern by declaring a "SingletonObject" base class which limits itself to only one instantiation. Then you derive any class that you want to be singletons from this base class. For example, you may implement a "publish/subscribe" pattern by declaring IPublisher and ISubscriber interfaces.
Now, if you really just want to just use the Decorator pattern on C# classes (as per the title of your question), what you are looking for is an automatic wrapper object generator. You can based your wrapper on an ExpandoObject, loop through the properties of the base object, and add properties to the ExpandoObject that simply delegates back to the base object. Then add new properties to the ExpandoObject on top of your base object. Voila! You get your auto-Decorator-Pattern wrapper class generator.
i'm adding comments to some csharp code, and i'm using the xml language provided by .net (or something). i have an interface, and some implementing classes. i have one method in the interface, and it has a comment. in the implementing classes there is no comment on the implementing method.
when one does it like this in java, javadoc automagically uses the interface comment when generating documentation. however, now that i build my project, i get the warning (transalted from swedish, sorry) "the xml comment for the visible type or member bla.blabla.blablabla() is missing (cs1591)". this is only a warning, so not so bad. but!!! it means no xml file was output, so i can't use sandcastle to generate a chm document file, which is my real goal here.... googling the error coded gave nothing :(
do i really have to copy the method comment to all implementing classes? that's like.... code duplication D: is there no way to get the behavior java offers?
I don't know of any way of getting it to happen at XML file generation time, but GhostDoc may well save you from performing the copying manually. I can't say I've used it myself though.
I agree that it would be a valuable feature... particularly if the base class (or interface) documentation changes after the derived classes have been implemented and documented.
You do have to copy the interfaces comments to the implementing class. Generally this is a good thing as the two comments should ideally be different - my opinion (and practise) on this can be summarised as the following:
Interface Comments - Explains what the method/property/etc is supposed/expected to do but should generally not proscribe how any specific implementation should behave
Implementing Class Comments - Explains what the method/property/etc actually does and may include some details of how this is done (typically in <remarks>)
VSdocman can resolve missing XML comments from implemented interfaces automatically when it generates documentation. Moreover, like GhostDoc, it can also explicitly copy inherited comments to the implementing method. Unlike Sandcastle, it's not free.
Well i dont know about Java but Sorry you will have to copy the interface's comments in the implemented class. here is no inbuilt way of doing it...
And yeah consider the suggestion given by JonSkeet
There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.
Does anyone has explanation why it is so?
A field is an implementation detail of a class and should not be exposed an its interface.
An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.
You can declare properties in interfaces instead.
UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.
I've rarely wanted to have an actual constant in an interface - they usually make more sense in classes. The practice of using a Java interface to just contain constants (in order to reduce typing in classes that use them) is nasty; I'd only put constants in interfaces where they were related to functionality within the interface itself.
However, on occasion I've thought it would be nice to be able to define an enum within an interface, if that's the only context in which the enum is anticipated to be used. Interestingly, VB allows this even though C# doesn't.
Effectively both of these would be a way of turning the interface into a "mini-namespace" in its own right. However, I can't say I've missed it very often when writing C#. As the C# team is fond of saying, features aren't removed - they're added, and the cost of adding a feature is very high. That means the feature really needs to pull its weight - there has to be a significant benefit before the feature is added. I personally wouldn't put this very high up on the list.
Related thought: it might be nice to be able to define a nested class within the interface, usually an implementation of the interface - either to express its contracts or to act as a "default" implementation for situations where there is such a thing.
and adding constants to interfaces is discouraged in Java too (according to Effective Java at least)
Adding constants to an interface is wrong and should almost never be done. In the past many people declared Interfaces with many constants and then made another class implement this interface so they could make use of the constants without qualifying said constant. This is of course another anti pattern and was only done because people were lazy. If you really want a constant in an interface define a method that returns that constant.
Ok the great thing about programming to an interface is that it allows you to interchange specific classes as long as the new classes implement everything in that interface.
e.g. i program my dataSource object to an interface so i can change it between an xml reader and a sql database reader.
does this mean ideally every class should be programmed to an interface?
when is it not a good idea to use an interface?
When the YAGNI principle applies.
Interfaces are great but it's up to you to decide when the extra time it takes developing one is going to pay off. I've used interfaces plenty of times but there are far more situations where they are completely unnecessary.
Not every class needs to be flexibly interchanged with some other class. Your system design should identify the points where modules might be interchangeable, and use interfaces accordingly. It would be silly to pair every class with an additional interface file if there's no chance of that class ever being part of some functional group.
Every interface you add to your project adds complexity to the codebase. When you deal with interfaces, discoverability of how the program works is harder, because it's not always clear which IComponent is filling in for the job when consumer code is dealing with the interface explicitly.
IMHO, you should try to use interfaces a lot. It's easier to be wrong by not using an interface than by using it.
My main argument on this is because interfaces help you make a more testable code. If a class constructor or a method has a concrete class as a parameter, it is harder (specially in c#, where no free mocking frameworks allow mocking non-virtual methods of concrete classes) for you to make your tests that are REAL unit tests.
I believe that if you have a DTO-like object, than it's overkill to use an interface, once mocking it may be maybe even harder than creating one.
If you're not testing, using dependency injection, inversion of control; and expect never to do any of these (please, avoid being there hehe), then I'd suggest interfaces to be used whenever you will really need to have different implementations, or you want to limit the visibility one class has over another.
Use an interface when you expect to need different behaviours used in the same context. I.e. if your system needs one customer class which is well defined, you probably don't need to use an ICustomer interface. But if you expect a class to comply to a certain behaviour s.a. "object can be saved" which applies to different knids of objects then you shoudl have the class implement an ISavable interface.
Another good reason to use an interface is if you expect different implementations of one kind of object. For example if ypu plan an SMS-Gateway which will route SMS's through several different third-party services, your classes should probably implent a common interface s.a. ISmsGatewayAdapter so your core system is independent from the specific implementation you use.
This also leads to 'dependecy injection' which is a technique to further decouple your classes and which is best implemented by using interfaces
The real question is: what does your class DO? If you're writing a class that actually implements an interface somewhere in the .NET framework, declare it as such! Almost all simple library classes will fit that description.
If, instead, you're writing an esoteric class used only in your application and that cannot possibly take any other form, then it makes no sense to talk about what interfaces it implements.
Starting from the premise of, "should I be implementing an interface?" is flawed. You neither should be nor shouldn't be. You should simply be writing the classes you need, and declaring what they do as you go, including what interfaces they implement.
I prefer to code as much as possible against an interface. I like it because I can use a tool like StructureMap to say "hey...get me an instance of IWidget" and it does the work for me. But by using a tool like this I can programatically or by configuration specify which instance is retrieved. This means that when I am testing I can load up a mock object that conforms to an interface, in my development environment I can load up a special local cache, when I am in production I can load up a caching farm layer, etc. Programming against an interface provides me a lot more power than not programming against an interface. Better to have and not need than need and not have applies here very well. And if you are into SOLID programming the easiest way to achieve many of those principles sort of begins by programming against an interface.
As a general rule of thumb, I think you're better off overusing interfaces a bit than underusing them a bit. Err on the side of interface use.
Otherwise, YAGNI applies.
If you are using Visual Studio, it takes about two seconds to take your class and extract an interface (via the context menu). You can then code to that interface, and hardly any time was spent.
If you are just doing a simple project, then it may be overkill. But on medium+ size projects, I try to code to interfaces throughout the project, as it will make future development easier.