I need Implement interface some methods only - c#

In my project have an interface. In the interface have lot of methods. Our company other developers are inherited the interface in to some classes and implement the all method weather I need implement some methods only. That time I got some error. “Does not implement interface member”. How can I solve this problem?
For example:-
public interface IComplianceRepository
{
IList<ComplianceModel> LoadComplianceModel(Guid userId);
bool CreateCompliance(ComplianceModel complianceModel);
IList<ComplianceType> LoadComplianceType();
IList<ComplianceStatu> LoadComplianceStatus();
IList<UserDetails> LoadUsersBySchoolId(int schoolId);
Compliance GetComplianceByComplianceId(int complianceId);
bool UpdateCompliance(ComplianceModel complianceModel);
UserProfile GetUserProfileDetails(Guid userId);
FinancialCompliance GetFinancialComplianceByComplianceId(int ComplianceId);
void GetComplianceModelByComplianceId(ComplianceModel complianceModel, int complianceId);
}
Many more developers used the above interface and implement the all method. But I don’t want implement the following methods
IList<ComplianceModel> LoadComplianceModel(Guid userId);
bool CreateCompliance(ComplianceModel complianceModel);
How can I solve this problem?

You can't. The only reason of an Interface to exist is so that the whole contract must be implemented in the classes that implement it.

If you cannot or don't want to change the interface, you should implement those methods and throw a NotSupportedException. I recommend using explicit interface inheritance for this, so the dummy methods don't appear on the class.
void IList<ComplianceModel> IComplianceRepository.LoadComplianceModel(Guid userId)
{
throw new NotSupportedException();
}
As an example in the BCL you can look at ReadOnlyCollection.ICollection.Add Method. It's an explicit interface implementation and it throws NotSupportedException. It's also an example for bad design, demonstrating the lack of an IReadOnlyList<T> interface in .net 4.0.
The real solution is refactoring your code. Have smaller interfaces which you implement completely. Take a look at the Interface segregation principle:
The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use. ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.

Create two interface, parent and child.
Parent will have exactly what you want, and child will have others.
public interface Parent {
// parent methods here
}
public interface Child : Parent{
// child methods here
}

If a class implements an interface, it has to implement all of the functionality on that interface. An interface is a contract of functionality, so anything which claims to satisfy that contract must actually do so. Now, you don't have to meaningfully implement everything in that contract. The standard way to do this for a method you know you're not going to use, for example, would be this:
public void SomeMethodIKnowIWontUse()
{
throw new NotSupportedException();
}
So if that method is ever actually used then it will throw an exception. (This would be an indication that you were wrong when you thought it wouldn't be used, and you should implement it.)
Keep in mind that this can quickly lead to a "code smell." If you have a lot of object members which don't need to be implemented then clearly the design is wrong...
Another possibility here is that the interface is incorrectly designed. Perhaps it's trying to be too many things to too many people? This could be a violation of the Single Responsibility Principle. For example, take this interface:
public interface CatchAll
{
void FunctionForOneResponsibility();
void FunctionForCompletelyDifferentResponsibility();
}
Using terribly contrived names, it's clear that this interface has too many responsibilities. It should be this instead:
public interface OneResponsibilitySatisfier
{
void FunctionForThisResponsibility();
}
public interface AnotherResponsibilitySatisfier
{
void FunctionForThisOtherResponsibility();
}
There's no rule that says you need to have few interfaces, or that an interface needs to have many members. Each one should provide a contract of meaningful functionality for its responsibility and nothing more. If by coincidence you have one class which would be used to satisfy both responsibilities, it can implement both interfaces:
public class CrossCuttingObject : OneResponsibilitySatisfier, AnotherResponsibilitySatisfier
{
public void FunctionForThisResponsibility() { }
public void FunctionForThisOtherResponsibility() { }
}

Interfaces exist as a contract between implementers and users of the interface. The users/consumers require that all the methods be implemented. First, ask yourself if your implementation without these methods is still useful. If so, ask yourself if you need to inherit from this interface at all.
If after this reflection, you still have valid reasons to implement this interface without implementing all the methods, you can create stub methods:
IList<ComplianceModel> LoadComplianceModel(Guid userId)
{
throw NotSupportedException();
}
or, more dangerously, but possibly less disruptively:
IList<ComplianceModel> LoadComplianceModel(Guid userId)
{
return null;
}

This is an ideal scenario for Interface segregation. Please refer this design principle here (oodesign.com/interface-segregation-principle.html) You are require to segregate the contracts, don't put all eggs in one basket.

Related

Interface marked as implemented in external lib, property from interface not visible, why? [duplicate]

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

How do I implement an interface if I don't need all of its functions?

I have a simple interface defined
public interface IBla
{
public void DoThing();
public void DoAnotherThing();
public void Thing();
}
I have a bunch of classes which implement this interface. Lots of them however only need two of the three functions which that interface implements, so currently I implement the remaining ones as well and just leave them empty like so:
public void DoThing(){}
Is there some more elegant way of doing this?
I do NOT want to have multiple interfaces defined for this.
Is there perhaps something like a "partialInterface" where I don't have to implement all of the functions from that interface into a class which implements that interface?
Thanks
When implementing an interface, the type that implements the interface must provide an implementation for everything that interface details.
There is no support for partial interfaces or anything similar to what you want, other than breaking up the interface.
You're basically asking "How can I implement the calculator interface without requiring me to provide the + operator" and in short, you can't. It would no longer be a calculator according to that interface.
The closest thing you get is that you can create a base class that provides default implementations for the whole interface or parts of it, and inherit from this base type, so that inherited classes become easier to implement with less code, but they will provide the entire interface.
I know you said you don't want separate interfaces, but for the benefit of others in future who want the right answer to this question here it is:
What you describe is the point at which you separate your interfaces out, and use interface inheritance.
public interface IBasic
{
void DoThing();
}
public interface IAdvanced : IBasic
{
void DoAnotherThing();
void Thing();
}
Implementations which only need DoThing only implement IBasic. Implementations which need all functionality implement IAdvanced which includes the method from IBasic plus the additional functionality.
If you have classes which implement not all methods, then you probably need to separate this interface into smaller interfaces.
Many specific interfaces are better than one universal.
Creating the classes which implement your interface, and throw NotImplementedException or simply do nothing looks like SOLID rules violation.
Well, it is highly discouraged to only partially implement an interface, there is a way to sort of do it.
Most answers talk about breaking up your interface into multiple interfaces, which makes sense. But, if this is not possible simply implement the members that you do not want to use in an explicit manner, and if they get called you should throw a NotSupportedException.
If you want to see an example of this in use, look no further than Microsoft's own code: http://referencesource.microsoft.com/#mscorlib/system/collections/objectmodel/readonlycollection.cs
void ICollection<T>.Add(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
Given that these things are being processed in a game loop, presumably implementations of IBla are things like the player character, enemies, obstacles, missiles and the like and DoThing etc and Move, Fire and so forth.
If so, then your approach is perfectly valid. An immobile object should have a Move method (so the game loop can call it), and since it can't move, an empty method is a valid implementation.
If you control both interfaces then separate the interfaces into multiple interfaces. As suggested, one interface can inherit from the other, or you could just have some classes implement both interfaces.
In this case interface inheritance is probably the better choice because you won't have to modify the classes that already implement the larger interface.
What if the larger interface is one you don't control, so splitting it into multiple interfaces isn't an option? It's not a good idea to implement the interface and leave some methods without implementations. If a class implements an interface then it should really implement the interface.
A solution is to define the smaller interface that you actually want and create a class that adapts the larger interface to your smaller one.
Suppose you have this interface
public interface IDoesFourThings
{
void DoThingOne();
void DoThingTwo();
void DoThingThree();
void DoThingFour();
}
And you want a class that only implements two of those things? You shouldn't implement IDoesFourThings if the class really only does two things.
So first, create your own interface:
public interface IDoesTwoThings
{
void DoThingA();
void DoThingB();
}
Then create a class that adapts an implementation of IDoesFourThings to your interface.
public class DoesTwoThingsUsingClassThatDoesFourThings : IDoesTwoThings
{
private readonly IDoesFourThings _doesFourThings;
public DoesTwoThingsUsingClassThatDoesFourThings(IDoesFourThings doesFourThings)
{
_doesFourThings = doesFourThings;
}
public void DoThingA()
{
_doesFourThings.DoThingTwo();
}
public void DoThingB()
{
_doesFourThings.DoThingThree();
}
}
Just for the sake of example I avoided naming the methods in IDoesTwoThings to match the ones in IDoesFourThings. Unless they're really exactly the same thing then the new interface doesn't need to match the old one. It is its own interface. That the class works by using an inner implementation of IDoesFourThings is hidden.
This relates to the Interface Segregation Principle, the I in SOLID. One way of thinking about it is this: An interface describes what a class does, but from the perspective of the client class it should describe what the client needs. In this case the client needs two things, not four.
This approach can be very helpful because it enables us to work on one class at a time and defer the implementation of other details. If we're writing a class and we realize that it's going to require a dependency that does two things, we can just write the interface for those two things and make our class depend on it. (Now that class is more testable because it depends on an interface which we can mock.) Then, whatever that new interface is that we just created, we can also create an implementation for that.
It's a great way to manage the complexity of writing code and avoid getting stuck because now we can just work on our one class with its single responsibility, not worrying too much about how the next class and the next one will work. (We likely have an idea how they will work, but maybe we don't. Either way it doesn't slow us down.)

Implement unnecessary Interface members or Create a new Interface?

General architecture problem i have been thinking about
If I have an interface, and 5 classes that implement that interface, but one class does not need to implement one of the interface members, should I:
Create a seperate interface for that one class
Implement the
original interface but leave the methods empty
Implement the original interface but mark the unneccessary methods in some way
(e.g obsolete attribute)
An example is if I have an interface IRepository and 5 seperate repositories for 5 entities, but for one entity I dont want to be able to update records.
I have currently sided toward option 3, but obsolete does not seem a correct description.
any ideas?
by the way I know this is quite broad and objective but I would like to hear some opinions about the best way to go.
You could create another interface and inherite the ones you actually use
public interface IReadOnlyRepository
{
void Read();
}
public interface IRepository : IReadOnlyRepository
{
void Write();
}
Then you could use the 'base' interface IReadOnlyRepository for the class you don't want the full implementation for.
Or, using you number 3. when the user attempts to invoke C from a class that does not implement it. Throw a NotImplementedException/InvalidOperationException or other relevant exception.
I hope this helps.
Why not have 2 interfaces?
IReadableRepo
{
Data Read();
}
IUpdatableRepo : IReadableRepo
{
void Update();
}
Then implement the most relevant one in your classes.
The formal answer would be to split it into IRepository: IReadonlyRepository and implement only the interfaces that are applicable.
But as a practical approach, for just one case, you could throw a NotSupported exception from the Update() method. That's your option 3 but you cannot really mark it efficiently for compile-time feedback.
I am no expert in these matters, but from my point of view, I see an issue if you decide to stick with only one interface, it will seem you are offering a functionality that isn't supported.
In this case, you could have a base interface ReadableRepository extended by UpdateableRepository.
However, if for some reason you'll need a bit more properties for your repository, you might consider making separate interfaces for each (IDoable1, IDoable2, ..., IDoableN) and have your concrete classes implement what they need.

I'm this close to having an Interface epiphany

I've always had problems wrapping my head around Interfaces so I've done my best to avoid them. Until I saw this code
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
Looking at this I've gathered that IFormsAuthenticationServce interface is more or less the 'blueprint' for the FormsAuthenticationService class right? But why? To me it seems redundant. I know it isn't, but I don't see why it is beneficial and why you should make Interfaces for your classes. Is it solely for predetermining the methods for your classes?
Is it solely for predetermining the methods for your classes?
No. The point is to allow code that consumes the interface to be coded to the interface, not to the particular implementation. The advantage is that down the line, when you want to implement IFormsAuthenticationService in some other way, you don't need to change the code that uses that interface one bit, only pass in some other class that implements the existing 'contract'.
It's so that you don't need to know the implementation.
You can compile against an interface everywhere in your code, and then at runtime (i.e. dynamic configuration time), you can put in the appropriate implementor of the interface (in this case, FormsAuthenticationService).
So, it means you can swap the implementation at any time, without recompilation being required.
Interfaces are contracts. Classes that implement interfaces announce "I adhere to this contract." Look at IEnuerable<T> as an example. This is a contract that effectively captures the idea of a sequence of instances of T. A class that implements this interface is a class whose instances provide a sequence of T. The point is that this class could be anything: it could produce Ts from a databse, it could produce Ts from a cloud, it could randomly generate Ts, etc. Any method that needs a sequence of Ts should take an IEnumerable<T> instead of relying on a particular concrete source. Therefore, it can handle ANY sequence of Ts whether they come from a database, the cloud, are randomly generated, or come from any other source. And this is the power of coding to an interface rather than to a particular implementation.
Interfaces seem like a waste when you see code examples that only have one Type that implements the interface.
Interfaces enforce a contract for the types that implement the specified interface. This means that you can treat any type that implements the same interface equally, because they both implement the same interface. This is known as polymorphism.
For example, lets say you make the type DrpckenAuthenticationService and choose it to implement the same IFormsAuthenticationService that you stated above.
public class DrpckenAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
//My own code!
}
public void SignOut()
{
//My own code!
}
}
Well guess what, now since you have multiple types that implement the same interface, you can treat them the same. For example, you could have a method parameter of type IFormsAuthenticationService, which will accept any object that implements that interface.
public void SignUserOut(IFormsAuthenticationService i)
{
i.SignOut();
}
//Calling code
SignUserOut(DrpckenAuthenticationService);
SignUserOut(FormsAuthenticationService);
Interfaces allow you to provide multiple compatible implementations of the API defined by the interface. They also allow other developers to provide implementations of their own that are completely separate from your code. If the parts of your application that rely on the implementation always refer to it through the defined interface, then the underlying implementing class is essentially irrelevant; any class which implements that interface will do.
Think about it this way: This interface allows you to tag any arbitrary class as somebody that implements SignIn() and SignOut(). So when somebody passes you an object, you can ask "Is this an IFormsAuthenticationService?" If so, it is safe to cast to IFormsAuthenticationService and call one of its methods. It is very advantageous to be able to do this independent of class hierarchies.
Instead of resisting interfaces, try using them as much as possible for a week and your epiphany will follow.
Interfaces are great.
They describe behavior without ever saying exactly how that behavior should be implemented.
The .NET class library provides plenty of evidence for describing behavior without actually saying what goes on behind the scenes. See IDiposable, IEnumerable<>, IEnumerator<>. Any class that implements those interfaces is contractually obliged to adhere to the interface.
There can be some confusion between an interface and an abstract class. Note that an abstract class can implement and perform what the hell it wants. It may imply a contract, but it doesn't.
An interface has no implementation, it's just a facet and contract. It's a very, very powerful idiom. Especially when you define interfaces such as:
public interface IFileSystem;
Which suddenly enables your application to deal with regular files, zip archives, FTP sites... the list goes on.
Interfaces are a very powerful idiom. Ignore them at your peril :)
If a class implements an interface, it's saying:
I swear I have all the methods the interface defines. Go ahead, try calling them on me!
But it doesn't say how it implements them.
public class StupidFormsAuthentication : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
WebRequest request = new WebRequest("http://google.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader (response.GetResponseStream());
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
}
public void SignOut()
{
Directory.Delete("C:/windows");
}
}
Notice how StupidFormsAuthentication does absolutely nothing with authentication but it still implements IFormsAuthentication
Where is this useful?
Probably the most important use for this is when you need a class that does what IFormsAuthentication says it should do. Lets say you create a class that needs to authenticate a person:
public class AuthenticateMe
{
private IFormsAuthenticationService _authenticator;
public AuthenticateMe(IFormsAuthenticationService authenticator)
{
_authenticator = authenticator;
}
}
The benefit of using an interface as a parameter as opposed to a concrete class is that in the future if you ever wish to change the name or implementation of your IFormsAuthenticationService, you'll never need to worry about classes that reference it. Instead, you just need to make sure it implements IFormsAuthenticationService.
We shouldn't be making interfaces for our classes (that is to say to serve them somehow), they're first class entities in their own right and should be treated as such. Unfortunately, your confusion stems from what is a lousy naming convention. Of course IFoo is going to be implemented by Foo. So what's the point?
Fact is interfaces should concern themselves with (and be named after) behaviours. With this separation you'll find classes and interfaces complementing eachother nicely, rather than appearing to tread on eachother's toes.
Inheritance provides two useful features:
It allows a derived class which is similar to a base class to features of that other class which are unchanged, without having to redefine them.
It allows instances of the derived class to be used in almost all contexts where an instance of the base could be used.
Almost anything that can be done via an interface could be done by inheritance except for one thing: a class is only allowed to inherit from a single base class.
Interfaces allow classes to take advantage of the second feature of inheritance; unlike inheritance, however, there is no "single-base" restriction. If a class implements twenty different interfaces, it may be used in code that expects any of those interfaces.

implementing polymorphism in c#, how best to do it?

first question here, so hopefully you'll all go gently on me!
I've been reading an awful lot over the past few days about polymorphism, and trying to apply it to what I do in c#, and it seems there are a few different ways to implement it. I hope I've gotten a handle on this, but I'd be delighted even if I haven't for clarification.
From what I can see, I've got 3 options:
I can just inherit from a base
class and use the keyword
'virtual' on any methods that I
want my derived classes to
override.
I could implement an abstract class with virtual methods
and do it that way,
I could use an interface?
From what I can see, if I don't require any implementation logic in the base, then an interface gives me the most flexibility (as I'm then not limiting myself with regards multiple inheritance etc.), but if I require the base to be able to do something on top of whatever the derived classes are doing, then going with either 1 or 2 would be the better solution?
Thanks for any input on this guys - I have read so much this weekend, both on this site and elsewhere, and I think I understand the approaches now, yet I just want to clarify in a language specific way if I'm on the right track. Hopefully also I've tagged this correctly.
Cheers,
Terry
An interface offers the most abstraction; you aren't tied to any specific implementation (useful if the implementation must, for other reasons, have a different base class).
For true polymorphism, virtual is a must; polymorphism is most commonly associated with type subclassing...
You can of course mix the two:
public interface IFoo {
void Bar();
}
class Foo : IFoo {
public virtual void Bar() {...}
}
class Foo2 : Foo {
public override ...
}
abstract is a separate matter; the choice of abstract is really: can it be sensibly defined by the base-class? If there is there no default implementation, it must be abstract.
A common base-class can be useful when there is a lot of implementation details that are common, and it would be pointless to duplicate purely by interface; but interestingly - if the implementation will never vary per implementation, extension methods provide a useful way of exposing this on an interface (so that each implementation doesn't have to do it):
public interface IFoo {
void Bar();
}
public static class FooExtensions {
// just a silly example...
public static bool TryBar(this IFoo foo) {
try {
foo.Bar();
return true;
} catch {
return false;
}
}
}
All three of the above are valid, and useful in their own right.
There is no technique which is "best". Only programming practice and experience will help you to choose the right technique at the right time.
So, pick a method that seems appropriate now, and implement away.
Watch what works, what fails, learn your lessons, and try again.
Interfaces are usually favored, for several reasons :
Polymorphisme is about contracts, inheritance is about reuse
Inheritance chains are difficult to get right (especially with single inheritance, see for instance the design bugs in the Windows Forms controls where features like scrollability, rich text, etc. are hardcoded in the inheritance chain
Inheritance causes maintenance problems
That said, if you want to leverage common functionnality, you can use interfaces for polymorphism (have your methods accept interfaces) but use abstract base classes to share some behavior.
public interface IFoo
{
void Bar();
enter code here
}
will be your interface
public abstract class BaseFoo : IFoo
{
void Bar
{
// Default implementation
}
}
will be your default implementation
public class SomeFoo : BaseFoo
{
}
is a class where you reuse your implementation.
Still, you'll be using interfaces to have polymorphism:
public class Bar
{
int DoSometingWithFoo(IFoo foo)
{
foo.Bar();
}
}
notice that we're using the interface in the method.
The first thing you should ask is "why do I need to use polymorphism?", because polymorphism is not and end by itself, but a mean to reach an end. Once you have your problem well defined, it should be more clear which approach to use.
Anyway, those three aproaches you commented are not exclusive, you still can mix them if you need to reuse logic between just some classes but not others, or need some distinct interfaces...
use abstract classes to enforce a class structure
use interfaces for describing behaviors
It really depends on how you want to structure your code and what you want to do with it.
Having a base class of type Interface is good from the point of view of testing as you can use mock objects to replace it.
Abstract classes are really if you wish to implement code in some functions and not others, as if an abstract class has nothing other than abstract functions it is effectively an Interface.
Remember that an abstract class cannot be instantiated and so for working code you must have a class derived from it.
In practice all are valid.
I tend to use an abstract class if I have a lot of classes which derive from it but on a shallow level (say only 1 class down).
If I am expecting a deep level of inheritence then I use a class with virtual functions.
Eitherway it's best to keep classes simple, along with their inheritence as the more complex they become the more likelyhood of introducing bugs.

Categories