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

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.

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.

Interface inheriting interface

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();

When to use variable of Interface type rather than concrete type

I have a class which derives from an Interface. Now the class has to implement all the methods in the Interfaces + it additionally defines 2 more methods.
Now my question is , what is the benefit/usecases of doing this:
IMyInterface varInt= new ConcreteImp();
over,
ConcreteImp varInt= new ConcreteImp();
I see this pattern used every where in code blocks, but not sure why this is used.
Benefit in using interfaces is in decreasing dependency of parts on concrete implementation of a software component. In one line you posted, you won't be able to see a benefit. Benefit can be gained in consumers of that interface.
Edit: You would be well to read this article on abstractions.
For example, lets say that you have a method which accepts an interface like so Rent(IMovie). Another person will be able to write implementation of Rent() method without knowing specifics of IMovie type which you will pass in when calling the method. You will then be able to create multiple different IMovie implementations which may have different method of billing, but Rent() method doesn't have to take care of that.
void Rent(IMovie movie)
{
var price = movie.Price();
movie.MarkReserved();
}
public interface IMovie { }
public class Oldie : IMovie
{
private decimal _oldieRate = 0.8;
public decimal Price()
{
return MainData.RentPrice * _oldieRate;
}
public decimal MarkReserved()
{
_oldiesDb.MarkReserved(this, true);
}
}
public class Blockbuster : IMovie
{
private decimal _blockbusterRate = 1.2;
public decimal Price()
{
return MainData.RentPrice * _blockbusterRate ;
}
public decimal MarkReserved()
{
_regularDb.MarkReserved(this, true);
}
}
This is example of why interfaces are useful, but is not very nice example of code design.
As a rule of thumb, you should write methods so that they require least input they need to work, and that their output provides as much information for others to use when they call it. For example, take a look at following signature:
public List<Entity> Filter(IEnumerable<Entity> baseCollection){ ... }
This method requests only IEnumerable<Entity> so it can take different collection types, like List<Entity>, Entity[] or custom types some tool returns. But you return List<Entity> so that right away you are not limiting caller to just enumerable elements. She can use Linq on return value right away for example.
There are more benefits, like in unit testing, where you can create mock objects and tell them how to behave during interaction with rest of the code. Although, you can do this with classes with virtual methods now.
Suppose that you want, elsewhere in the code, to be able to assign a different implementation of IMyInterface to the varInt variable. Then that variable needs to be declared with type IMyInterface.
Alternatively, if you want to make it clear to any code readers that all you intend to do with varInt is use the interface defined by IMyInterface, then the type declaration makes that clear.
When you need to enforce functionality in the derived class use interface.
and when you need to pass data from super class to subclass then you use concrete class. Its the basic oop idea behind interface and subclass.
In your concrete example I would say it doesn't matter as much since you are using new and creates a concrete type. When you start using dependency injection it starts to be more useful.
A scenario where it is more useful looks like the following:
public SomeResultType DoSomething(ISomeType obj)
{
//to something with obj
// return someResultType
}
The above can be called using any type as long as it implements ISomeType. But in your example using the new keyword I would instead use var. You will still be able to treat it as type it implements since it inherit that type.
assume that IMyInterface have "Draw" method, now all derived classes have to implement "Draw" method. if you have a class "Engine" with a method "Render(IMyInterface shape)", you have only to call the "Draw" method no matter what the shape is. and every shape Draw itself as he wants.
you can take a look at Design Patterns and you can see the magic of interfaces ;)

abstract method use vs regular methods

I would like to know the difference between two conventions:
Creating an abstract base class with an abstract method
which will be implemented later on the derived classes.
Creating an abstract base class without abstract methods
but adding the relevant method later on the level of the derived classes.
What is the difference?
Much like interfaces, abstract classes are designed to express a set of known operations for your types. Unlike interfaces however, abstract classes allow you to implement common/shared functionality that may be used by any derived type. E.g.:
public abstract class LoggerBase
{
public abstract void Write(object item);
protected virtual object FormatObject(object item)
{
return item;
}
}
In this really basic example above, I've essentially done two things:
Defined a contract that my derived types will conform to.
Provides some default functionality that could be overriden if required.
Given that I know that any derived type of LoggerBase will have a Write method, I can call that. The equivalent of the above as an interface could be:
public interface ILogger
{
void Write(object item);
}
As an abstract class, I can provide an additional service FormatObject which can optionally be overriden, say if I was writing a ConsoleLogger, e.g.:
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
}
By marking the FormatObject method as virtual, it means I can provide a shared implementation. I can also override it:
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
protected override object FormatObject(object item)
{
return item.ToString().ToUpper();
}
}
So, the key parts are:
abstract classes must be inherited.
abstract methods must be implemented in derived types.
virtual methods can be overriden in derived types.
In the second scenario, because you wouldn't be adding the functionality to the abstract base class, you couldn't call that method when dealing with an instance of the base class directly. E.g., if I implemented ConsoleLogger.WriteSomethingElse, I couldn't call it from LoggerBase.WriteSomethingElse.
The idea of putting abstract methods in a base class and then implementing them in subclasses is that you can then use the parent type instead of any specific subclass. For example say you want to sort an array. You can define the base class to be something like
abstract class Sorter {
public abstract Array sort(Array arr);
}
Then you can implement various algorithms such as quicksort, mergesort, heapsort in subclasses.
class QuickSorter {
public Array sort(Array arr) { ... }
}
class MergeSorter {
public Array sort(Array arr) { ... }
}
You create a sorting object by choosing an algorithm,
Sorter sorter = QuickSorter();
Now you can pass sorter around, without exposing the fact that under the hood it's a quicksort. To sort an array you say
Array sortedArray = sorter.sort(someArray);
In this way the details of the implementation (which algorithm you use) are decoupled from the interface to the object (the fact that it sorts an array).
One concrete advantage is that if at some point you want a different sorting algorithm then you can change QuickSort() to say MergeSort in this single line, without having to change it anywhere else. If you don't include a sort() method in the parent, you have to downcast to QuickSorter whenever calling sort(), and then changing the algorithm will be more difficult.
In the case 1) you can access those methods from the abstract base type without knowing the exact type (abstract methods are virtual methods).
The point of the abstract classes is usually to define some contract on the base class which is then implemented by the dervied classes (and in this context it is important to recognize that interfaces are sort of "pure abstract classes").
Uhm, well, the difference is that the base class would know about the former, and not about the latter.
In other words, with an abstract method in the base class, you can write code in other methods in the base class that call that abstract method.
Obviously, if the base class doesn't have those methods... you can't call them...
An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality...
And of course, if you override a virtual method, you can always refer to the parent method by calling base.myVirtualMethod()
Okay, when you see a method like this:
A.Foo();
What you really have (behind the scenes) is a signature like this.
Foo(A x);
And when you call A.Foo() you're really calling Foo(this) where this is a reference to an object of type A.
Now, sometimes you'd like to have Foo(A|B|C|D...) where Foo is a method that can take either a type A, or B, or C, or D. But you don't want to worry about what type you're passing, you just want it to do something different based on the type that was passed in. Abstract methods let you do that, that's their only purpose.

I think I missed something on the "Programming to an interface" concept

So I am still very new to C# and using interfaces, and when I thought I understood them I realized I don't completely. The confusion I have found that I am seeking some clarification here for is, when you create an interface, and have a class inherit from it
public Interface ISomeInterface
{
//some methods/properties
}
public class FooClass : ISomeInterface
{
//implemented ISomeInterfaces methods/properties
}
And you use this class object in an implementation somewhere in your program
public class BarClass
{
private ISomeInterface _someInterface;
public BarClass(ISomeInterface someInterface)
{
_someInterface = someInterface;
}
//rest of class
}
My confusion is why do I see it setup this way. I thought that I would have instantiated a new object of type FooClass, as well as used an object of type FooClass in the constructor as such:
public class BarClass
{
private FooClass _fooClass;
public BarClass(FooClass fooClass)
{
_fooClass = fooClass;
}
//rest of class
}
What am I missing to understanding this? I didn't think I would directly be declaring objects of an Interface?
Thanks in advance.
The idea is that BarClass should not be tightly coupled to a specific implementation of ISomeInterface.
If you use this:
public BarClass(FooClass fooClass)
it means that the BarClass can work only with this specific FooClass implementation and nothing else. Whereas if you use:
public BarClass(ISomeInterface fooClass)
now the BarClass is no longer tightly coupled to FooClass. This means that the consumer of the BarClass can now pass any implementation of the interface he wants as long as it respects the defined contract (interface). So if he wants FooClass he passes an instance of FooClass, but if he is not satisfied with FooClass he can write his own implementation and pass it to the constructor and from the point of view of the BarClass this is absolutely transparent (it doesn't need to be modified).
The weak coupling between your classes is one of the most fundamental aspects of OOP as it allows you to easily replace one component with another without having to rewrite your entire application.
Suppose FooClass wrote something to a database. You'd like to test BarClass without having to actually set up a database. If you created a different TestFoo that implemented the same interface, you could pretend to be the database and more easily test your class; BarClass wouldn't have to know that it wasn't talking to the 'real' FooClass.
Do you have a C/C++ background? Then you should be aware that
private ISomeInterface _someInterface;
would be written as
private:
ISomeInterface& _someInterface;
In C++ (assuming you have an abstract base class called ISomeInterface).
This means you are storing a reference to an object implementing ISomeInterface not such an object itself. The advantage of this is that you can pass ANY object to BarClass that implements ISomeInterface which gives you more flexibility, e.g. for unit testing.
By using the interface definition instead of the concrete implementation, your code is now more loosely coupled. This technique is used in dependency injection.
In addition, this comes in handy when you need to need to implement FooClass differently. If you used the concrete implementation, you will need to make code changes where ever you have declared FooClass. Programming against the interface shields you from the effects of such changes.
One of the main benefit to program to ISomeInterface instead of FooClass, is that you might probably change your implementation of FooClass. For example, consider a database driven blog application:
interface IBlogStorage{
getPosts();
}
you then have a class like:
class XMLBlogSotrage: IBlogStorage{}
and suppose you implement everything to the interface. later on, you think XML is too slow and you want to use RDBMS, then:
class MsSQLBlogStorage:IBlogStorage{}
In this case, you don't need to change anything in other codes, you just need to create a new class and plug it in! Those already existed codes, doesn't need to bother where is the storage.
Another way of thinking about the interplay between interfaces and classes is to flip them upside down. That means to start with classes first. Let's say you have several classes that expose a method called "Sort()". Then you have another class that has a method that requires references to these classes and in turn calls their "Sort()" methods. Instead of having several methods with different parameters, you can create and attach an interface to those classes (very quick fix as these classes already contain the implementation).
A.Sort()
B.Sort()
C.Sort()
interface ISortable {void Sort();}
A : ISortable
B : ISortable
C : ISortable
D.SortSomething(ISortable foo)
{
foo.Sort()
}
Maybe this is too abstract. My favorite use of interfaces is enabling my classes to participate in foreach loops.
class SomeCollection : IEnumerable
{
List<SomeItem> _items = new List<SomeItem>();
// This is the only code I need to enable this class to participate in foreach loop.
public Enumerator GetEnumerator()
{
return _items.GetEnumerator();
}
}
Once you discover how interfaces can simplify your codes, you can even begin creating interfaces before writing your classes.

Categories