The new extensions in .Net 3.5 allow functionality to be split out from interfaces.
For instance in .Net 2.0
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
Can (in 3.5) become:
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.
The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)
Any other reasons not to regularly use this pattern?
Clarification:
Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a .SplitToDictionary() - similar to .Split() but taking a key-value delimiter too)
I think there's a whole best practice debate there ;-)
(Incidentally: DannySmurf, your PM sounds scary.)
I'm specifically asking here about using extension methods where previously we had interface methods.
I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.
Is this what MS has done to IEnumerable and IQueryable for Linq?
Extension methods should be used as just that: extensions. Any crucial structure/design related code or non-trivial operation should be put in an object that is composed into/inherited from a class or interface.
Once another object tries to use the extended one, they won't see the extensions and might have to reimplement/re-reference them again.
The traditional wisdom is that Extension methods should only be used for:
utility classes, as Vaibhav mentioned
extending sealed 3rd party APIs
I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.
Versioning. One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.
As a concrete example, the first version of a library might define an interface like so:
public interface INode {
INode Root { get; }
List<INode> GetChildren( );
}
Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:
public interface IChildNode : INode {
INode Parent { get; }
}
However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:
public static class NodeExtensions {
public INode GetParent( this INode node ) {
// If the node implements the new interface, call it directly.
var childNode = node as IChildNode;
if( !object.ReferenceEquals( childNode, null ) )
return childNode.Parent;
// Otherwise, fall back on a default implementation.
return FindParent( node, node.Root );
}
}
Now all users of the new library can treat both legacy and modern implementations identically.
Overloads. Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.
Instead extension methods can be used to provide the trivial overload implementations:
public interface ILongMethod {
public bool LongMethod( string s, double d, int i, object o, ... );
}
...
public static LongMethodExtensions {
public bool LongMethod( this ILongMethod lm, string s, double d ) {
lm.LongMethod( s, d, 0, null );
}
...
}
Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)
Edit: A related post by Joe Duffy: Extension methods as default interface method implementations
I think the best thing that extension methods replace are all those utility classes that you find in every project.
At least for now, I feel that any other use of Extension methods would cause confusion in the workplace.
My two bits.
There is nothing wrong with extending interfaces, in fact that is how LINQ works to add the extension methods to the collection classes.
That being said, you really should only do this in the case where you need to provide the same functionality across all classes that implement that interface and that functionality is not (and probably should not be) part of the "official" implementation of any derived classes. Extending an interface is also good if it is just impractical to write an extension method for every possible derived type that requires the new functionality.
I see separating the domain/model and UI/view functionality using extension methods as a good thing, especially since they can reside in separate namespaces.
For example:
namespace Model
{
class Person
{
public string Title { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
}
namespace View
{
static class PersonExtensions
{
public static string FullName(this Model.Person p)
{
return p.Title + " " + p.FirstName + " " + p.Surname;
}
public static string FormalName(this Model.Person p)
{
return p.Title + " " + p.FirstName[0] + ". " + p.Surname;
}
}
}
This way extension methods can be used similarly to XAML data templates. You can't access private/protected members of the class but it allows the data abstraction to be maintained without excessive code duplication throughout the application.
A little bit more.
If multiple interfaces have the same extension method signature, you would need to explicitly convert the caller to one interface type and then call the method. E.g.
((IFirst)this).AmbigousMethod()
Ouch. Please don't extend Interfaces.
An interface is a clean contract that a class should implement, and your usage of said classes must be restricted to what is in the core Interface for this to work correctly.
That is why you always declare the interface as the type instead of the actual class.
IInterface variable = new ImplementingClass();
Right?
If you really need a contract with some added functionality, abstract classes are your friends.
I see a lot of people advocating using a base class to share common functionality. Be careful with this - you should favor composition over inheritance. Inheritance should only be used for polymorphism, when it makes sense from a modelling point of view. It is not a good tool for code reuse.
As for the question: Be ware of the limitations when doing this - for example in the code shown, using an extension method to implement GetChildren effectively 'seals' this implementation and doesn't allow any IHaveChildren impl to provide its own if needed. If this is OK, then I dont mind the extension method approach that much. It is not set in stone, and can usually be easily refactored when more flexibility is needed later.
For greater flexibility, using the strategy pattern may be preferable. Something like:
public interface IHaveChildren
{
string ParentType { get; }
int ParentId { get; }
}
public interface IChildIterator
{
IEnumerable<IChild> GetChildren();
}
public void DefaultChildIterator : IChildIterator
{
private readonly IHaveChildren _parent;
public DefaultChildIterator(IHaveChildren parent)
{
_parent = parent;
}
public IEnumerable<IChild> GetChildren()
{
// default child iterator impl
}
}
public class Node : IHaveChildren, IChildIterator
{
// *snip*
public IEnumerable<IChild> GetChildren()
{
return new DefaultChildIterator(this).GetChildren();
}
}
Rob Connery (Subsonic and MVC Storefront) implemented an IRepository-like pattern in his Storefront application. It's not quite the pattern above, but it does share some similarities.
The data layer returns IQueryable which permits the consuming layer to apply filtering and sorting expression on top of that. The bonus is being able to specify a single GetProducts method, for example, and then decide appropriately in the consuming layer how you want that sorting, filtering or even just a particular range of results.
Not a traditional approach, but very cool and definitely a case of DRY.
One problem I can see is that, in a large company, this pattern could allow the code to become difficult (if not impossible) for anyone to understand and use. If multiple developers are constantly adding their own methods to existing classes, separate from those classes (and, God help us all, to BCL classes even), I could see a code base spinning out of control rather quickly.
Even at my own job, I could see this happening, with my PM's desire to add every bit of code that we work on to either the UI or the data access layer, I could totally see him insisting on 20 or 30 methods being added to System.String that are only tangentially-related to string handling.
I needed to solve something similar:
I wanted to have a List<IIDable> passed to the extensions function where IIDable is an interface that has a long getId() function.
I tried using GetIds(this List<IIDable> bla) but the compiler didn't allow me to do so.
I used templates instead and then type casted inside the function to the interface type. I needed this function for some linq to sql generated classes.
I hope this helps :)
public static List<long> GetIds<T>(this List<T> original){
List<long> ret = new List<long>();
if (original == null)
return ret;
try
{
foreach (T t in original)
{
IIDable idable = (IIDable)t;
ret.Add(idable.getId());
}
return ret;
}
catch (Exception)
{
throw new Exception("Class calling this extension must implement IIDable interface");
}
Related
What are the differences in implementing interfaces implicitly and explicitly in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.
Here's an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.
Reason #1
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Reason #2
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
The class's primary interface, which is used by web page developers; and
A "hidden" interface used by the presenter that I develop to handle the control's logic
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
But's It's Not a Silver Cannonball
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to
understand some ramifications that
exist when using EIMIs. And because of
these ramifications, you should try to
avoid EIMIs as much as possible.
Fortunately, generic interfaces help
you avoid EIMIs quite a bit. But there
may still be times when you will need
to use them (such as implementing two
interface methods with the same name
and signature). Here are the big
problems with EIMIs:
There is no documentation explaining how a type specifically
implements an EIMI method, and there
is no Microsoft Visual Studio
IntelliSense support.
Value type instances are boxed when cast to an interface.
An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
When required, as per disambiguation or needing an internal interface
Discourages "programming to an implementation" (Reason 1 by Jon)
Problems
It's not all fun and happiness. There are some cases where I stick with implicits:
Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
(My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).
In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
This code compiles and runs OK, but the Title property is shared.
Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.
Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.
If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.
Public Overridable Function Foo() As Integer Implements IFoo.Foo
Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
Not as nice.
The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.
// Given:
internal interface I { void M(); }
// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }
// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }
The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.
Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
I've found myself using explicit implementations more often recently, for the following practical reasons:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways
Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI
No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too
Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync
I am working on a C# project that sits on top of a 3rd party CMS. The team is leveraging Dependency Injection to promote loose coupling between classes.
I have the need to "extend" the apis of the CMS with common functions that are used in several pages.
What makes it interesting is these common functions have multiple dependencies.
In this case, is it more appropriate to extend this functionality using static extension methods or by creating new interfaces?
Context
Let's say the 3rd Party has two interfaces IContentLoader and IPageSecurity that work with Page objects:
namespace 3rdParty.Api
{
public class Page{}
public interface IContentLoader{
T LoadItem<T>(Guid id) where T : Page;
}
public interface IPageSecurity
{
bool CurrentUserCanReadPage(Page p);
}
}
And I want to write a common method like:
public IEnumerable<T> LoadAllChildPagesTheUserCanRead(Guid id) where T:Page
{
//load page, recursively collect children, then
//filter on permissions
}
(I admit this example is a bit trite)
Extension Methods
I could create a static extension method using Property Injection:
public static class IContentLoaderExtensions
{
public static Injected<IPageSecurity> PageSecurity {get;set;}
public static IEnumerable<T> LoadAllChildItems(
this IContentLoader contentLoader, Guid id){}
}
This method is then very discoverable, we use IContentLoader often so it's easier for a team member to find it. However, I have read that Property Injection is generally less beneficial than Constructor Injection and should be avoided if possible.
Wrapper
On the other hand, I could create a Wrapper:
public class AdvancedContentLoader
{
public AdvancedContentLoader(IContentLoader c, IPageSecurity p){
//save to backing fields
}
IEnumerable<T> LoadAllChildItems(Guid id){}
}
This approach allows for Constructor Injection, which avoids the potential hazards of Property Injection, but makes the method less discoverable. The consumer would need to know to depend on AdvancedContentLoader instead of using the IContentLoader they are use to.
Summary
In this case where a method has multiple dependencies, is it better to promote discoverability by using an extension method and take whatever brittleness may come from using Property Injection? Or is Construction Injection so favorable that I should create a wrapper class at the cost of making the method harder to find?
I would lean more towards the wrapper class but I would create another interface for it. I would name it similar so developers can find it.
public interface IContentLoaderWithPageSecurity : IContentLoader
{
IEnumerable<T> LoadAllChildItems<T>(IContentLoader contentLoader, Guid id) { }
}
New interface but same starting name so intellisense can help developers. Also this interface has to implement the 3rd party interface.
I would change your AdvancedContentLoader class to implement this interface and chain all calls to IContextLoader to 3rd party implementation and handle just the specific methods it needs to handle.
public class AdvancedContentLoader : IContentLoaderWithPageSecurity
{
private readonly IContentLoader _internalContentLoader;
private IPageSecurity _pageSecurity;
public AdvancedContentLoader(IContentLoader contentLoader, IPageSecurity pageSecurity)
{
_internalContentLoader = contentLoader;
_pageSecurity = pageSecurity;
}
// Chain calls on the interface to internal content loader
public T LoadItem<T>(Guid id) where T : Page
{
return _internalContentLoader.LoadItem<T>(id);
}
public IEnumerable<T> LoadAllChildItems<T>(IContentLoader contentLoader, Guid id)
{
// do whatever you need to do here
yield break;
}
}
The benefits of this is if you are using DI Container you can just register IContentLoaderWithPageSecurity interface to the class and you are still coding to an interface.
The naming convention helps the developers find it with intellisense, if the namespace of the class is in the using directive.
The new interface implements the old one so existing code base that needs IContentLoader you can still pass down IContentLoaderWithPageSecurity into those methods.
I would only lean towards extension methods if I didn't require a new dependency and could just just what is already there - otherwise you have to get "smart" and do property injection or something like the ConditionalWeakTable to hold extra state for the class.
I agree with Wiktor Zychla that this starts to become peoples subjective opinions.
I suggest a decorated content loader. This approach follows SRP principle, where you don't mix responsiblities - I still have a content loader and when I want to implemenet loading multiple elements, I delegate this to another class.
public class DecoratedContentLoader : IContentLoader
{
IContentLoader c;
IPageSecurity p;
public DecoratedContentLoader(IContentLoader c, IPageSecurity p)
{
this.c = c;
this.p = p;
}
public T LoadItem<T>(Guid id) where T : Page
{
var page = c.LoadItem<T>( id );
if ( p.CanUserReadPage( p ) )
return p;
// throw or return null
}
}
As you can see, this uses the security provider but still implements a single item provider interface.
Thus, another class responsible for loading multiple items can just take IContentProvider as an argument and use either the bare one or the decorated one without distinguishing between the two.
public class AdvancedContentLoader
{
// no need for additionak parameters, works
// with any loader, including the decorated one
public AdvancedContentLoader( IContentLoader c )
{
//save to backing fields
}
IEnumerable<T> LoadAllChildItems(Guid id){}
}
So, my initial reaction to this is that there might be a bit of over-thinking going on here. If I understand your question correctly, you are trying to figure out the easiest way to extend a third party API. In this case, the API has an interface that you like, IContentLoader, and your goal is to add another method to this interface which enables it:
in addition to loading a given page (defined by Guid),
to recursively load all child pages as well,
so long as the user has permission (which is in the responsibility of IPageSecurity).
According to Microsoft,
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Which, if I understand, is exactly what you are trying to do here. I will admit that the structure and function for IPageSecurity does not make much sense to me, and that could be the reason behind the confusion. Bottom line, is there any reason why you would choose not to go this route? Perhaps your purpose is complicated by your example.
Implementing Interface just provide the skeleton of the method. If we know the exact signature line of that method, in this case
what is the requirement to implement Interface?
This is the case in which Interface has been implemented
interface IMy
{
void X();
}
public class My:IMy
{
public void X()
{
Console.WriteLine("Interface is implemented");
}
}
This is the case in which Interface has not been implemented
public class My
{
public void X()
{
Console.WriteLine("No Interface is implemented ");
}
}
My obj = new My();
obj.X();
Both the approaches will produce the same result.
what is the requirement to implement Interface?
The purpose of interfaces is to allow you to use two different classes as if they were the same type. This is invaluable when it comes to separation of concerns.
e.g. I can write a method that reads data from an IDataReader. My method doesn't need to know (or care) if that's a SqlDataReader, and OdbcDataReader or an OracleDataReader.
private void ReadData(IDataReader reader)
{
....
}
Now, lets say I need that method to process data coming from a non-standard data file. I can write my own object that implements IDataReader that knows how to read that file, and my method again, neither knows nor cares how that IDataReader is implemented, only that it is passed an object that implements IDataReader.
Hope this helps.
You can write multiple classes that implement an interface, then put any of them in a variable of the interface type.
This allows you to swap implementations at runtime.
It can also be useful to have a List<ISomeInterface> holding different implementations.
There are two purposes of inheritance in .net:
Allow derived classes to share the base-class implementations of common functionality
Allow derived-class objects to be substituted for base-class objects anywhere the latter would be accepted.
Unlike some languages (C++, for example) which allow multiple inheritance, .net requires every class to have precisely one parent type (Object, if nothing else). On the other hand, sometimes it's useful to have a class be substitutable for a number of unrelated types. That's where interfaces come in.
An object which implements an interface is substitutable for an instance of that declared interface type. Even though objects may only inherit from one base type, they may implement an arbitrary number of interfaces. This thus allows some of the power of multiple inheritance, without the complications and drawbacks of full multiple-inheritance support.
You've provided a very basic example, which is probably why you're having trouble understand why. Examine something like this:
public interface IDbColumn
{
int domainID { get; set; }
}
public static IEnumerable<T> GetDataByDomain<T>(
IQueryable<T> src) where T:IDbColumn
{
string url = HttpContext.Current.Request.Url.Host;
int i = url == "localhost" ? 1 : 2;
return src.Where(x => x.domainID == i|| x.domainID == 3);
}
domainID is a physical column in every table that will reference this method, but since the table type isn't known yet there's no way to have access to that variable without an interface.
Heres simple example wich helped me to understand interfaces:
interface IVehicle
{
void Go();
}
public class Car:IVehicle
{
public void Go()
{
Console.WriteLine("Drive");
}
}
public class SuperCar:IVehicle
{
public void Go()
{
Console.WriteLine("Drive fast!!");
}
}
IVehicle car = new Car();
car.Go(); //output Drive
car = new SuperCar();
car.Go(); //output Drive fast!!
Say you have three classes, A, B, C.
A needs to accept an argument. Either B or C can be passed through.
The best way to do this is create an interface that B and C share
Well interfaces are not meant to be used with just one class, they are used accross many classes to make sure that they contain a set of methods.
a good way to visualize it is to think about driver abstraction, being able to run 1 query that can be interoperated by several different database servers.
interface DatabaseDriver
{
public function connect(ConnectionDetails $details){}
public function disconnect(){}
public function query(Query $query){}
public function prepareQuery(SQLQuery $query){}
}
and then your actual drivers would use the interface so that the database object can be assured that that the selected driver is able to perform the tasks required.
class MySqlDriver extends Database implements DatabaseDriver{}
class AccessDriver extends Database implements DatabaseDriver{}
class MsSqlDriver extends Database implements DatabaseDriver{}
hope this helps.
Note: Code in PHP
Over the past few years I've been on projects where we've run into a similar problem in our object hierarchy that always seems to cause problems. I was curious if anyone here knew of a classical OOP (Java, C#, PHP5, etc) design pattern that could gracefully handle this situation.
Say we have an existing system. This system has, among other things, two types of entities, each modeled with an individual class. Let's say
Customer
SalesRepresentative
For historical reasons, neither of these classes inherit from the same base class or share a common interface.
The problem I've seen is, inevitably, a new feature gets specced out that requires us to treat the Customer and the SalesRepresentative as the same type of Object. The way I've seen this handled in the past is to create a new class that includes a member variable for both, and then each method will operate on the objects differently depending on which is set
//pseudo PHPish code
class Participator
{
public $customer;
public $salesRepresentative;
public function __construct($object)
{
if(object is instance of Customer)
{
$this->customer = $object;
}
if(object is instance of SalesRepresentative)
{
$this->salesRepresentative = $object;
}
}
public function doesSomething()
{
if($customer)
{
//We're a customer, do customer specific stuff
}
else if($salesRepresentative)
{
//We're a salesRepresentative, do sales
//representative specific stuff
}
}
}
Is there a more graceful way of handling this type of situation?
Maybe a Wrapper can be used here. Create a Wrapper Interface say ParticipatorWrapper that specifies the new functionality and build concrete Wrappers for each class, say CustomerWrapper and SalesRepresentativeWrapper that both implement the new functionality.
Then simply wrap the object in its appropriate wrapper and write code that targets the ParticipatorWrapper.
Update: Javaish code:
interface ParticipatorWrapper{
public void doSomething();
}
class CustomerWrapper implements ParticipatorWrapper{
Customer customer;
public void doSomething(){
//do something with the customer
}
}
class SaleREpresentativeWrapper implements ParticipatorWrapper{
SaleRepresentative salesRepresentative;
public void doSomething(){
//do something with the salesRepresentative
}
}
class ClientOfWrapper{
public void mymethod(){
ParticipatorWrapper p = new ParticipatorWrapper(new Customer());
p.doSomething();
}
}
This is an alternative to that Vincent's answer, taking an opposite sort of approach. As I note below, there are some downsides, but your specific problem may obviate those and I think this solution is simpler in those cases (or you may want to use some combination of this solution and Vincent's).
Rather than wrapping the classes, introduce hooks in the classes and then pass them the functions. This is a reasonable alternative if you're looking to do the same thing with the same data from both classes (which I am guessing you are, based on lamenting that the two classes don't have a shared superclass).
This is using Visitor instead of Wrapper. Javaish this be something like:
public <Output> Output visit(Vistor<Output> v) {
return v.process(...all shared the fields in Customer/SalesRep...);
}
And then you have a Visitor interface which all your functions inherit from that looks like:
interface Visitor<Output> {
public Output process(...shared fields...);
}
There are someways to chop what gets passed to your Visitor, but the involves introducing new classes to specify which inputs to use, which becomes wrapping anyways, so you might as well use Vincent's answer.
The downside to this solution is if you do something that alters the structure of the class fields, you can buy yourself lots of refactoring, which is less of a problem in Vincent's answer. This solution is also a little bit less useful if you're making modifications to the data stored in the Customer/SalesRep instance, as you'd effectively have to wrap those inside the Visitor.
I think you could apply the concept of mixins to your classes to get the functionality you want.
I am new to C#. Recently I have read an article.It suggests
"One of the practical uses of interface is, when an interface reference is created that can
work on different kinds of objects which implements that interface."
Base on that I tested (I am not sure my understanding is correct)
namespace InterfaceExample
{
public interface IRide
{
void Ride();
}
abstract class Animal
{
private string _classification;
public string Classification
{
set { _classification = value;}
get { return _classification;}
}
public Animal(){}
public Animal(string _classification)
{
this._classification = _classification;
}
}
class Elephant:Animal,IRide
{
public Elephant(){}
public Elephant(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Elephant can ride 34KPM");
}
}
class Horse:Animal,IRide
{
public Horse(){}
public Horse(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Horse can ride 110 KPH");
}
}
class Test
{
static void Main()
{
Elephant bully = new Elephant("Vertebrata");
Horse lina = new Horse("Vertebrata");
IRide[] riders = {bully,lina};
foreach(IRide rider in riders)
{
rider.Ride();
}
Console.ReadKey(true);
}
}
}
Questions :
Beyond such extend, what are the different way can we leverage the elegance of Interfaces ?
What is the Key point that I can say this can be only done by interface (apart from
multiple inheritances) ?
(I wish to gather the information from experienced hands).
Edit :
Edited to be concept centric,i guess.
The point is, you could also have a class Bike which implements IRide, without inheriting from Animal. You can think of an interface as being an abstract contract, specifying that objects of this class can do the things specified in the interface.
Because C# doesn't support multiple inheritance (which is a good thing IMHO) interfaces are the way you specify shared behavior or state across otherwise unrelated types.
interface IRideable
{
void Ride();
}
class Elephant : Animal, IRideable{}
class Unicycle: Machine, IRideable{}
In this manner, say you had a program that modeled a circus (where machines and animals had distinct behavior, but some machines and some animals could be ridden) you can create abstract functionality specific to what is means to ride something.
public static void RideThemAll(IEnumerable<IRideable> thingsToRide)
{
foreach(IRideable rideable in thingsToRide)
ridable.Ride();
}
As Lucero points out, you could implement other classes that implement IRide without inherting from Animal and be able to include all of those in your IRide[] array.
The problem is that your IRide interface is still too broad for your example. Obviously, it needs to include the Ride() method, but what does the Eat() method have to do with being able to ride a "thing"?
Interfaces should thought of as a loose contract that guarantees the existance of a member, but not an implementation. They should also not be general enough to span "concepts" (eating and riding are two different concepts).
You are asking the difference between abstract classes and interfaces. There is a really good article on that here.
Another great advantage is lower coupling between software components. Suppose you want to be able to feed any rideable animal. In this case you could write the following method:
public void Feed(IRide rideable)
{
//DO SOMETHING IMPORTANT HERE
//THEN DO SOMETHING SPECIFIC TO AN IRide object
rideable.Eat();
}
The major advantage here is that you can develop and test the Feed method without having any idea of the implementation of IRide passed in to this method. It could be an elephant, horse, or donkey. It doesn't matter. This also opens up your design for using Inversion of Control frameworks like Structure Map or mocking tools like Rhino Mock.
Interfaces can be used for "tagging" concepts or marking classes with specifically functionality such as serializable. This metadata (Introspection or Reflection) can be used with powerful inversion-of-control frameworks such as dependency injection.
This idea is used throughout the .NET framework (such as ISerializable) and third-party DI frameworks.
You already seem to grasp the general meaning of Interfaces.
Interfaces are just a contract saying "I support this!" without saying how the underlying system works.
Contrast this to a base or abstract class, which says "I share these common properties & methods, but have some new ones of my own!"
Of course, a class can implement as many interfaces as it wants, but can only inherit from one base class.