Interface inheriting interface - c#

I have a hierarchy.
public interface IIncomingMessage : IMessage
{
String Source { get; set; }
void ProcessMessage();
}
public interface IOutgoingMessages : IMessage
{
void SendMessage();
}
I have a client that uses a Static CreateMessage method to generate my message.
IMessage message = MessageFactory.CreateMessage("incomingA");
messageA.ProcessMessage();
However the only way I can do this is if I add ProcessMessage() to IMessage. However if I do this then I must implement this in IOutgoingMessage.
Now as I write this I see that I could just get rid of IMessage.. should I? Or is there a better way of doing this?

Based on how you're using the CreateMessage factory, you are expecting that ProcessMessage is a common method to all IMessage types. Based on how you expect your code to work, I would say that IMessage should have a ProcessMessage method interface defined.
However, in looking at the small snippet of code, it seems to me that your intent is not to always process a message, but only do so if it's an IIncomingMessage implementation. So your factory approach isn't going to work. T. Kiley's suggestion of having two factory methods of CreateInboundMessage and CreateOutboundMessage may make more sense since you have different behaviors for both types of messages. Those methods then would return IIncomingMessage and 'IOutgoingMessage` instances and then you can process them or handle them accordingly.
IMessage is being used, currently, as a marker interface. If you see a need for this - whether it's a constraint for generics (e.g. MyCollection<T> where T : IMessage), then keep it. But if it's really not describing behavior or a common set of properties/methods or if it's not to be used as a useful marker, then I'm not sure what benefit it provides.
Again, this is based off just seeing a little bit of code. I'm assuming there's more behavior and functionality behind the scenes. Good luck!!

I'll try to simplify by giving another example of this scenario:
public class Animal
{
void Run();
}
public class Giraffe : Animal
{
void ExtendNeck();
}
public class Monkey : Animal
{
void EatBanana();
}
Now is it okay if I now add EatBanana() to Animal? As you noticed yourself, not all IMessage implementors ProcessMessage() and in this example not all animals EatBanana(). What is another way to accomplish what you are trying to do? Only use IMessage if you do have common functionalities to be shared among your classes. If you don't have any, there is no need for an inteface. Have YAGNI in mind. You may add it later if there are common functionalities. If you want to create an IncomingMessage and call IncomingMessage specific methods, then just create a strongly typed IncomingMessage and work with it. You may not even need a static factory method.

You can use different classes which don't inherit anything and completely separate the process. If you do that you will loose several advantages of using subclassing in this case. There might be similar properties between them which will make it easier to reference one versus the other if they both extend a common class. As for your method issue with these subclasses, you can simply have your parent class declare a common method (let's call it ProcessMessage() ), and simply have each subclass overwrite the behavior of such method. This way you don't need to have to different methods but simply two different definitions. Simple polymorphism concepts.

(assuming 'MessageFactory.CreateMessage("incomingA")' return an object of type IIncomingMessage)
either use var
var message = MessageFactory.CreateMessage("incomingA");
message.ProcessMessage();
or cast the result
IMessage message = MessageFactory.CreateMessage("incomingA");
if (!(message is IIncommingMessage))
throw new InvalidOperationException();
(message as IIncommingMessage).ProcessMessage();

Related

Implement a class from Interface having implemented methods as static (.NET) [duplicate]

Why was C# designed this way?
As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.
If classes wish to implement that behavour in a shared method, why shouldn't they?
Here is an example of what I have in mind:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
Assuming you are asking why you can't do this:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.
To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.
My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.
For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):
...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.
Note that Lippert does leave room for a so-called type method:
That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).
but is yet to be convinced of its usefulness.
Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.
Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.
For example:
Repository GetRepository<T>()
{
//need to call T.IsQueryable, but can't!!!
//need to call T.RowCount
//need to call T.DoSomeStaticMath(int param)
}
...
var r = GetRepository<Customer>()
Unfortunately, I can come up only with "ugly" alternatives:
Use reflection
Ugly and beats the idea of interfaces and polymorphism.
Create completely separate factory class
This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.
Instantiate and then call the desired interface method
This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.
Example:
public class Customer
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
void SomeOtherMethod()
{
//do work...
}
}
in order to use instantination for solving the static interface problem we need to do the following thing:
public class Customer: IDoSomeStaticMath
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
//dummy instance
public Customer() { IsDummy = true; }
int DoSomeStaticMath(int a) { }
void SomeOtherMethod()
{
if(!IsDummy)
{
//do work...
}
}
}
This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!
I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:
string DoSomething<T>() where T:ISomeFunction
{
if (T.someFunction())
...
}
Merely being able to have static methods implement an interface would not achieve what you want; what would be needed would be to have static members as part of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:
Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default().
For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.
None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized "new" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).
Short-sightedness, I'd guess.
When originally designed, interfaces were intended only to be used with instances of class
IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();
It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.
(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.
To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.
The above arguments all seem to miss this point about contracts.
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Because the purpose of an interface is to allow polymorphism, being able to pass an instance of any number of defined classes that have all been defined to implement the defined interface... guaranteeing that within your polymorphic call, the code will be able to find the method you are calling. it makes no sense to allow a static method to implement the interface,
How would you call it??
public interface MyInterface { void MyMethod(); }
public class MyClass: MyInterface
{
public static void MyMethod() { //Do Something; }
}
// inside of some other class ...
// How would you call the method on the interface ???
MyClass.MyMethod(); // this calls the method normally
// not through the interface...
// This next fails you can't cast a classname to a different type...
// Only instances can be Cast to a different type...
MyInterface myItf = MyClass as MyInterface;
Actually, it does.
As of Mid-2022, the current version of C# has full support for so-called static abstract members:
interface INumber<T>
{
static abstract T Zero { get; }
}
struct Fraction : INumber<Fraction>
{
public static Fraction Zero { get; } = new Fraction();
public long Numerator;
public ulong Denominator;
....
}
Please note that depending on your version of Visual Studio and your installed .NET SDK, you'll either have to update at least one of them (or maybe both), or that you'll have to enable preview features (see Use preview features & preview language in Visual Studio).
See more:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
https://blog.ndepend.com/c-11-static-abstract-members/
https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:~:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition.
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
Because interfaces are in inheritance structure, and static methods don't inherit well.
What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.
There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.
Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.
You can think of the static methods and non-static methods of a class as being different interfaces. When called, static methods resolve to the singleton static class object, and non-static methods resolve to the instance of the class you deal with. So, if you use static and non-static methods in an interface, you'd effectively be declaring two interfaces when really we want interfaces to be used to access one cohesive thing.
To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the "so-called type method":
When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:
interface IDataRow {
string GetDataSTructre(); // How to read data from the DB
void Read(IDBDataRow); // How to populate this datarow from DB data
}
public class DataTable<T> : List<T> where T : IDataRow {
public string GetDataStructure()
// Desired: Static or Type method:
// return (T.GetDataStructure());
// Required: Instantiate a new class:
return (new T().GetDataStructure());
}
}
The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.
FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.
Interfaces are abstract sets of defined available functionality.
Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.
If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: http://en.wikipedia.org/wiki/Object-oriented). For this reason, static methods aren't permitted in interfaces.
Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.
I had a bunch of Static Business Layer classes that implemented CRUD methods like "Create", "Read", "Update", "Delete" for each entity type like "User", "Team", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the "Create", "Read", "Update", "Delete" operations from the base class. I had to use a Singleton because of the Static limitation.
Most people seem to forget that in OOP Classes are objects too, and so they have messages, which for some reason c# calls "static method".
The fact that differences exist between instance objects and class objects only shows flaws or shortcomings in the language.
Optimist about c# though...
OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a
static public bool IsHandled(XElement xml)
function which is called in turn on each class.
The function should be static as otherwise we waste time creating inappropriate objects.
As #Ian Boyde points out it could be done in a factory class, but this just adds complexity.
It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.
However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.
So it is a minor potential feature which on balance is probably best left out.
The fact that a static class is implemented in C# by Microsoft creating a special instance of a class with the static elements is just an oddity of how static functionality is achieved. It is isn't a theoretical point.
An interface SHOULD be a descriptor of the class interface - or how it is interacted with, and that should include interactions that are static. The general definition of interface (from Meriam-Webster): the place or area at which different things meet and communicate with or affect each other. When you omit static components of a class or static classes entirely, we are ignoring large sections of how these bad boys interact.
Here is a very clear example of where being able to use interfaces with static classes would be quite useful:
public interface ICrudModel<T, Tk>
{
Boolean Create(T obj);
T Retrieve(Tk key);
Boolean Update(T obj);
Boolean Delete(T obj);
}
Currently, I write the static classes that contain these methods without any kind of checking to make sure that I haven't forgotten anything. Is like the bad old days of programming before OOP.
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
Static Methods within an Interface are allowed as of c# 9 (see https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9).
I think the short answer is "because it is of zero usefulness".
To call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.
I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.
Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.
public interface IZeroWrapper<TNumber> {
TNumber Zero {get;}
}
public class DoubleWrapper: IZeroWrapper<double> {
public double Zero { get { return 0; } }
}
As per Object oriented concept Interface implemented by classes and
have contract to access these implemented function(or methods) using
object.
So if you want to access Interface Contract methods you have to create object. It is always must that is not allowed in case of Static methods. Static classes ,method and variables never require objects and load in memory without creating object of that area(or class) or you can say do not require Object Creation.
Conceptually there is no reason why an interface could not define a contract that includes static methods.
For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).
A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.
So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).
An interface is an OOPS concept, which means every member of the interface should get used through an object or instance. Hence, an interface can not have static methods.
When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.

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.)

How to create method interface with variable parameters / different method signatures?

I'm trying to create an interface to a common class, but the implementation classes can have different parameters.
e.g.
public interface IViewModel
{
//...
void ResetReferences();
}
// and then, in my class implementations, something like this:
public class LocationViewModel : IViewModel
{
public void ResetReferences(List<StateProvinces> stateProvinces) //...
}
public class ProductViewModel : IViewModel
{
public void ResetReferences(List<Color> colors, List<Size> sizes) //...
}
So notice that I want to standardize on the ResetReferences naming convention. I'm pretty sure I can't do this, but is there a design pattern that could work? e.g. in my interface, something like below?
// variable parameters
void ResetReferences(params object[] list);
But then how do I make I do type checking or having it call the actual method signature that I want, etc?
Maybe an interface is the wrong thing to use? Maybe just a base class and some coding conventions?
Thanks,
Replace your args lists with objects that implement a related interface:
public interface IViewModel
{
//...
void ResetReferences(IResetValues vals);
}
I should add that, IMO, ResetReferences() should not take an argument... it should reset to some default value that would be specific to the individual type(s) that implement your interface..."Reset" being the word that means, to me, "restore to initial state"...adding args implies that you can control that.
The purpose of an interface is to have client code know about the interface and be oblivious of the implementation. If your implementations require special treatment when called, the client code need to know what implementation it is calling and then the whole purpose of the interface is lost.
Unless I misunderstand totally what you're trying to accomplish, you're down the wrong road.
If the parameters can be different, then it isn't really a common interface. Put it this way: does the caller need to know the implementation class? If so, you've lost the loose coupling benefits of interfaces.
One option is to encapsulate the parameters into another type, and make the class generic on that type. For example:
public interface IViewModel<T>
{
void ResetReferences(T data);
}
Then you'd encapsulate the List<Color> colors, List<Size> sizes into one type, and possibly put List<StateProvinces> stateProvinces in another.
It's somewhat awkward though...
You will need to implement the interface method, but you can still do what you want
public class LocationViewModel : IViewModel
{
public void ResetReferences(List<StateProvinces> stateProvinces) // ...
void IViewModel.ResetReferences() // ...
}
You would have to have both methods in the interface (and have the one not correct for an instance throw a non-supported exception), or have the interface inherit from two other interfaces to the same effect.
An interface definition is the entire signature.
It may also be possible to pass an object as a parameter (perhaps derived from a ParameterProvider base class) so that the object encapsulates the dynamic nature and still allows the interface to be static. But that that point you're basically working around the type system anyway.

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