How can I determine at runtime if an interface member is implemented? - c#

I have an interface called IStructuredReader that reads some structured data from a file and displays it in a form. It has a member called Sync() that, when implemented, scans the data for a user-specified data pattern.
Some implementations of IStructuredReader don't have sync capability. Those implementations throw NotImplementedException for the Sync() method. I would like to be able to check for this method being implemented, so that I can dim the button on the form if it is not.
I can think of a number of ways that this could be done, all of which seem clumsy and complicated:
Separate the Sync method into its own interface, inherit it for those implementations that support the capability, and attempt to cast the reader object to it to identify the capability,
Write a NotImplementedAttribute, decorate the member with it, and check for the presence of the attribute using Reflection,
Add a HasSyncCapability boolean property to the interface.
Is there a canonical way this is done?

This sounds like you really should have two interfaces. Your Sync() method is obviously adding functionality over your base interface, which suggests that this is really a separate concern, as it's not a requirement of IStructuredReader. I would suggest adding a second interface for the types which support this, which would then be easy to check for in your view layer.

The canonical way is for the interface to expose the methods that will be implemented, so the cleanest solution I see is to create another interface called maybe Syncronizable with just that method. If your object implements that interface you know the method is there, and this is not clumsy at all. Using reflection or the extra attribute are indeed not as clean as solutions, but it doesn't mean you shouldn't go for those if it makes your life easier ;)

Related

How can I prevent methods from being added to a class?

I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).
Is there any way to achieve this?
Use reflection and write a unit test that fails if a model-class has methods.
Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.
I believe you are trying to solve a procedural issue with code where you should be using communication.
Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!
I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.
You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.
However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.
You don't need to use a struct to prevent additions to a class. You can use the sealed keyword
public sealed class MyDTOObject { ... }
Now, you can not inherent a class and also prevent inheritance (which is essentially what you're asking). The very fact of inheriting MyDTOObject is creating a new class which is based off of not equal to, or restricted, or defined in any way by the implementation of MyDTOObject.
You can use an abstract class, to force derived classes to implement certain methods, but not the other way around.
If you want to prevent others from deriving from your class and implementing helper methods, you must use the sealed keyword, or mark the class internal.
You may prevent the class being extended or inherited by marking it final that way nobody would be able to extend your class and hence not being able to add any behavior. But stop and ask yourself whether you want to do that or not, because then you'd be signing an invisible contract that everything ever required by the class is written in the class and this class needs no further addition.
To be clear, I was talking in Java context.

Should extension methods only be used on classes whose code you don't have access to?

Should extension methods only be used on classes whose code you don't have access to?
I'm struggling to come up with a reason to have extension methods versus making it partial and adding the classes in an external file.
My specific scenario is as follows: I have classes that represent entities in a database via EF. I'm debating making the classes it renders partial and adding my own methods. Are extension methods a more valid alternative approach or are they not intended to be used when you have access to the code of the class you are extending?
The canonical counter-example is extension methods on an interface, as even if you control the source, there is no implementation. See: Linq.
But, yes, generally speaking, if you control the source of the concrete class, it is not unreasonable to expect to add the functionality to the class directly rather than using an extension method, if it makes sense for the functionality to actually be part of the class instance.
On the other hand, and coming back to your situation, you might consider neither approach. Your entities are data models, I would not add methods to those models, but rather encapsulate that functionality elsewhere. Those models exist to encapsulate your data, logic that might operate with or against that data might be better served in a different unit. But that really depends upon what your methods are doing, and also assuming they're not something like a trivial wrapper over one or more properties, for example.
Apart from the ability to provide extensions to interfaces, I use extension methods to add 'members' to a class that work using only the class' public interface. So if a method needs access to a private/protected member, it will become a class member, if not an extension method. This keeps the classes themselves small and focused...
No.
You may have a class that works fine in ninety percent of your projects. By adding an extension method you don't 'pollute' the original class but can still leverage it in the other ten percent of your projects.
Should extension methods only be used on classes whose code you don't have a access to?
Not necessarily. There are situations where extension methods can still help. I recently had an issue with the xml serializer where it could serialize an object that had a method that made use of a linq / lamba expression. Moving the method to an extension method resolved that. I like to use extension methods on DTOs also.
You might want to look at How Non-Member Functions Improve Encapsulation. There are some C++ specifics, but main idea applies to other OO languages as well. In short: the less methods you have in a class the easier it is to understand who and how changes private class state.

OnSerializing/OnSerialized/OnDeserializing/OnDeserialized why not an interface?

I've been doing some reading on serialization in .NET and started wondering what was the main reason of implementing the OnSerializing/OnSerialized/OnDeserializing/OnDeserialized functionality as attributes in contrast to an interface. I can think of some pros and cons but I'm probably missing something crucial so I wanted to know what outweighed.
In favor of an interface:
Method signatures are checked at compile time (using an attribute on a method with an incorrect signature causes a runtime exception)
No two methods could be declared for a single event on a class level (decorating two methods with the same attribute causes a runtime exception)
In favor of attributes:
No need to declare 4 methods if we want to react to a single event
An interface would not be as good because there is then no automatic way for each class in a hierarchy on top of the interface to provide its own implementation unless:
The base class declares the methods as virtual
Each deriving class re-implements the interface
Then there is the added complication of identifying each class's implementation - the reflection is harder.
Furthermore, once the interface is brought in, the implication is that all classes in a hierarchy are serializable, but this is not always, nor should it always, be the case. It is entirely proper to derive a non serializable class from a serializable base (in controlled circumstances) - but this is effectively prevented through the use of either interfaces or virtual methods.
The use of attributes, then, provide the tersest, most expressive and actually most flexible way to implement serialization.
Here's another reason in favor of attributed methods over an interface.
If an interface were used, it would be possible for a subclass to override the method implementation, hiding the base class's implementation. Of course, the subclass's implementation would have a responsibility to explicitly invoke the overridden method, but it's usually a bad idea to make proper program behavior contingent upon programmer responsibility.
The way things are implemented now, a subclass's serialization triggered method will not hide the base class's. The serialization framework is responsible for making sure they all get called in proper order, and the serialization framework is trustworthy.
Because the implementation can be partial. If all those method reside in the same interface you have 4 methods that you maybe dont need but you have to provide an implementation for them. On the other hand you could have one interface for each method but then you have 4 interfaces that you sometimes need to implement. That's a lot of methods and interfaces that can be avoided in this way.

How should i refactor this?

so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.

Is it possible to force an update of an Interface?

In resharper is it possible to force an update of an interface?
Basically I have a class that inherits from an interface but this class is constantly changing so I need to reflect the changes in the interface otherwise VS complains that I am not implementing something as the signature of the method has changed.
I was wondering if there is a way in resharper to say "Update this class with its interface" ?
Any ideas?
Although not the best way to design, sometimes it is necessary to update the interface based on the modified class.
You can update the interface using resharper's Pull Members Up option.
Use the Pull Members Up option in the refactor menu
Select the interface you would like to update as the base type
Select the members you would like to add to the interface
The members have now been added to the interface.
If you use ReSharper to modify the method, it can/will also modify the interface definition.
For instance, if you use ReSharper's Rename functionality on the method, the interface definition of it will get renamed. Additionally, if you use ReSharper's Change Signature functionality on the method, it asks you if you want to do the refactoring on the interface as well.
If you're changing signature of a method defined in an interface, change it via Refactor - Change Signature.... ReSharper will then ask you if you want to change signature of an interface method.
Other than that, I cannot imagine how would ReShaper know what and how to update.
Letting the interface follow the implementation is the exact wrong direction. First, you should define in your interface, what you need, then implement it in the backing class. You shouldn't expect a tool to support undesired workflows instead...
If you go the right way, R# will give you all support you ever need: You can refactor existing methods via Refactor|Rename..., Refactor|Change Signature... and Implement Members.

Categories

Resources