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
Syncmethod 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
HasSyncCapabilityboolean 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 ofIStructuredReader. 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.