Interface implementation and common function - c#

I have the following requirement,
There will be 2(or more) different classes to perform same kind of operation(in different ways). Therefore I decided to create an interface. Then I implemented these 2 classes with my interface.
Now, from another class I will be using the object of type Interface and calls functions. Everything works fine.
Then a new requirement came to create a common functionality that applies to both classes.
I don't want to define same function in both classes. And interface dont allows function definition.
First I thought abstract class will be useful. Because it allows function definition and abstract functions. But abstract classes cant be instantiated and also I need to create objects with individual class types.
Sorry I cant find a simple way to define my problem. It feels like a solution that spring framework provides. But I need to know how to acheive this from a Java/C# application.

It sounds like you want an abstract class implementing the common functionality, but still have two concrete classes for the distinct functionality. You may or may not still want to keep the interface as well. So the options are:
Interface
^
|
Abstract
class
^
/ \
Concrete Concrete
class 1 class 2
or just
Abstract
class
^
/ \
Concrete Concrete
class 1 class 2
Code which wants to use these classes just uses the interface or abstract class. How you configure which concrete class to use were will depend on your exact requirements - but presumably you'd already tackled that in the earlier version.

A common pattern for this is:
Define the interface (as you've done).
Create an abstract class which implements the common functionality in terms of the non-common functionality.
Extend this abstract class to provide the non-common functionality.
A lot of JDK classes do this. For instance, the List<T> interface has an AbstractList<T> abstract class, which is extended to provide both ArrayList<T> and LinkedList<T>.
A simple (if contrived) example would be something like:
interface IntThingy {
int getValue();
int getDoubeValue();
}
abstract class AbstractIntThingy implements IntThingy {
#Override
public int getDoubleValue() {
return getValue() * 2;
}
}
class ConstantFourtyTwo extends AbstractIntThingy {
#Override
public int getValue() {
return 42;
}
}
class ConstantIntThingy extends AbstractIntThingy {
private final int value;
ConstantIntThingy(int value) {
this.value = value;
}
#Override
public int getValue() {
return value;
}
}
Note that once Java 8 arrives, you'll be able to define methods in interfaces. These are commonly known as "defender methods." When that happens, you may not need the abstract class -- depending on whether that common functionality needs to maintain its own state (interfaces still won't be able to define instance state). But for now, the interface-abstract-concrete pattern often works well.

You can try to avoid using simple interface and use strategy pattern:
http://en.wikipedia.org/wiki/Strategy_pattern

Create a concrete class (or better abstract class) that implements your interface, and contains your "common functionality", Now you can extend this class (Hierarchy) with two (or more) classes.
there are many more ways of designing this requirement.
And I am not sure If mine is best either.

Just to add on to Jon Skeet's answer, you need to think as to what kind of relationship your classes have with the interface or the intended abstract class. If the relationship is between the behaviour laid out in the interface is has-a then the interface is the right choice, and if it is an is-a relationship, you can go with an abstract class.
In another scenario, you can also check if the relationship is has-a, and the new common functionality that you want to implement is an is-a relationship, then apart from option by Jon, you can use something like this:
Abstract
class
^
/ \
Interface Interface
\ /
Concrete Concrete
class 1 class 2
for e.g.:
interface IParent{}
abstract class Parent{}
class Child1: Parent, IParent{}
class Child2: Parent, IParent{}
It all depends how you design your classes for future use.

Related

(Regular Class + interface) vs Abstract class

I recently encountered a question on abstract class.
Functionality of Abstract classes can be achieved by using combination of (Regular class with Protected Constructor + an interface).
What is the benefit of using Abstract Class over (Regular class with protected constructor + interface).
IMHO, Purpose of Abstract class to have common feature that needs to be available across the class hierarchy. It can pose restriction on sub-classes to implement certain features by Abstract methods. It can allow Sub-Classes to override the common behavior.
Abstract Class doesn't serve a purpose of as concrete object. So, It doesn't allow to instantiate the abstract class.
However,We can achieve same thing using Regular Class + interface.
Mark Regular Class constructor as protected, So object can't be created alone
provide default implementation of common features and mark them virtual in case if they need to be overridden by sub class.
Use interface to force sub-classes to implement certain features.
So, Is there any extra feature which Abstract class offer?
I could not think of any other. Interviewers was trying to know what other benefits Abstract class have over Regular Class with protected constructor + interface.
A lot of good reasons. Let's start with an unambiguous one:
public abstract class Smell
{
public abstract string GetAdjective();
public string GetDescription()
{
return "I smell " + GetAdjective();
}
}
public class NastySmell : Smell
{
public override string GetAdjective() { return "really nasty"; }
}
Pretty simple. The abstract class has a function, GetDescription - which relies on the presence of an abstract method GetAdjective.
How could you do this with ProtectedConstructor+Interface? You can't have Smell implement the interface (for lots of reasons, but a big one being that any derived classes would also inherit the implementation and wouldn't be required to implement anything new) - but that means that it's function can't refer to the method:
public interface SmellInterface
{
string GetAdjective();
}
public class Smell
{
protected Smell() { }
public string GetDescription()
{
// how do I call GetAdjective here? I have no reference to it!
}
}
But here's another, even more compelling reason:
public abstract class SomeFancyClass
{
protected string name;
protected string server;
protected abstract string implementer { get; }
public string Generate()
{
if (name == "something")
HandleGlobally(name);
else
HandleSpecifically(name);
}
public void HandleGlobally(string server)
{
// code
}
public abstract void HandleSpecifically(string server);
}
... if you make this class a combo ProtectedConstructorClass + Interface, you split up code into two separate spots - and suddenly, you have to look through two halves to get the full picture of what's going on!
public interface AbstractHalf
{
// data property of 'implementer'
// method of 'HandleSpecifically()
}
public class NonabstractHalf
{
// data fields of 'name' and 'server'
// methods of 'Generate()' and 'HandleGlobally'
}
... why would you want to do this? Your class is a distinct, logical entity. Why would you split it up into two separate parts: the non-abstract versus the abstract? It'd just make it harder to read and troubleshoot. And it'd get worse, the more code and abstract declarations were made in the class.
The main benefit of the abstract class is to force the developer to create a subclass that inherits from the abstract class in order to use base/shared functionality and fields.
You cannot directly new-up an abstract class. You can new-up a regular class + interface, and you are not forced to inherit or override anything in the base.
With an abstract class, you can reduce the number of files - i.e. no interfaces, but most folks would probably like to keep those for registration with an IoC container and dependency injection.
One thing that I can think of is that by using an abstract class you can force a specific implementation simply by not marking a method or property as virtual, while using an interface you can't prevent classes from implementing the interface but not derive from your base class.
Another benefit of using an abstract class is that you can simply add functionality to your abstract class without having to worry about having all your derived classes implementations - again, since you can't prevent a class from implementing an interface without deriving from your base class.
Also, an abstract class can have protected fields, methods, events etc', but an interface can't.
It all boils down to the fact that you can't force classes that implement your interface to derive from your "regular" base class.
First of all, there is many questions and answers about differences between Abstract Class and Interfaces like: this. There are a lot of remarkable answers. But most of them are about programming and syntax.
I want to look from Design Perspective:
I think that Abstract Class can not play the Role of Interface (+ Regular Class)
in Software Design.
Abstract Class:
The main goal of Abstract Class is Abstraction Principle. To overcome this complexity, Abstract classes are used to make Hierarchies in similar looking classes. All classes in the hierarchy are extending base classes functionalities and extending types of base classes.
Interface:
However, Interfaces are used for Interactions between classes. These classes can be similar or not. They can be from different hierarchies and different types.
Also, they are huge difference between inheriting from a class (even Abstract class) and implementing an interface. Interfaces are not TYPES. They are shared boundary across which two or more separate components of a computer system exchange information.

Two different Inheritance-chains without breaking the DRY-principle

I have a problem with using the right inheritance-chain without loosing good parts of the DRY-principle.
Given the following structure:
abstract class A is my base for all classes
abstract class B : A is my base for all classes that can have special features (made available through B)
Now, I need to have two new classes which share the same features. But one is of type A whilst the other one is of type B. (This can not be changed!)
Both classes should have a method SetSize().
So at the end there would be class C:A and D:B, both to have the same SetSize method.
Question: How would I create a base-class, intermediate layer to have the SetSize()-method only declared/implemented once (DRY)?
I guess something about using interfaces or some static helper-classes to implement the logic of SetSize()?
Are there any patterns or best-practices to achieve this behavior?
You can't do this via inheritance in C# because it doesn't support multiple inheritance; the tool the language gives you for this scenario is interfaces:
public interface
{
void SetSize(Size size);
}
public SizableA: A, ISizable { ... }
public SizableB: B, ISizable { ... }
Also bear in mind that inheritance should be used when the types in the inheritance chain have a is a relationship (a Cat is an Animal, a B is an A, etc.) while interfaces are preferred when completely unrelated classes have a very specific common behavior; IEquatable, IComparable, IDisposable, etc. Your SetSize behavior seems to fit better in this last category as it doesn't seem to be a functionality specific to A or B.
Now, if both SizableA and SizableB should share the same implementation of SetSize then the best solution is to use composition or simply delegate functionality:
public interface ISizable
{
void SetSize(Size size, ISetSizeProvider provider); //Alternatively inject provider in SizableA and SizableB's constructor to get composition.
}
Make an abstract class include SetSize() method and common properties of A and B classes.Then A and B classes inherit the abstract class.

Whats the difference between an abstract class and interface? When would you want to use them? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use an interface instead of an abstract class and vice versa?
Difference between Interface, abstract class, sealed class, static class and partial class in C#?
public class Guru{
public Enemy(int x, int y, int health, int attack, ...) {
...
}
...
}
public class UserDefinedClass extends Enemy {
...
}
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
An Interface cannot implement methods.
An abstract class can implement methods.
An Interface can only inherit from another Interface.
An abstract class can inherit from a class and one or more interfaces.
An Interface cannot contain fields.
An abstract class can contain fields.
An abstract class can not be instantiated but that can contain code whereas interface only contains method definitions but does not contain any code. you need to implement all the methods defined in the interface.
If your logic will be the same for all the derived classes, it is best to go for a abstract class in stead of an interface.
You can implement multiple interfaces but only inherit from one class.
oAn interface implies the minimal coupling possible between the object and the code that wants to consume it. An abstract class implies some stronger relationship between the classes, and probably some commonality of implementation.
An interface should be used when we want to separate concerns as much as possible (eg Dependency Injection)
An abstract class should be used to model a common family of objects where a strong relationship exists in the domain

Reason to use BOTH abstract classes and interfaces? (Abstract class implements interface)

Recently I have come across a curious pattern in some code. We know that there is a time and a place for everything, especially when it comes to the issue of ABCs and interfaces, but this just seems redundant to me.
// This describes a person....
public interface IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BasePay { get; set; }
public string Address { get; set; }
}
// And so does this, but it also uses the interface....
public abstract class Person : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BasePay { get; set; }
public string Address { get; set; }
}
// This uses both ?!
public class CoalMiner : Person, IPerson
{
public CoalMiner()
{
BasePay = 10000;
}
}
Can anybody think of what the specific advantage of using both and ABC and an interface that define the same members be?
Personally, I feel that using an interface to describe a "noun", such as a person, it typically a poor design choice.
Interfaces should be used for contracts - all people are always a Person, so an abstract class makes more sense here. Interfaces could be added for behaviors attached to specific types of people, or to allow a Person to be used in a certain way by fulfilling a contract (ie: Person : IComparable<Person>).
Having both the IPerson interface and the Person base class allows you certain freedoms, as long as you are passing around objects under the IPerson interface rather than the Person base class.
Base classes tend to implement common code that should be used by all descendants of that base class. That's fine if that's what you want, but one might run into a case where an entirely different implementation of IPerson is needed, where the base class Person is not used at all. Now you have 2 class hierarchies that have IPerson in common, and things still work. You would not be able to do that with Person only.
Another good reason for the redundancy of always having an interface would be for COM interop.
A situation where both the interface and the ABC makes sense is when using the decorator pattern. The ABC is used to provide common implementation code for the different concrete implementation classes. All implementation classes are probably derived from the ABC.
A decorator, which wraps an existing instance and tweaks the functionality of it would typically only implement the interface and not derive from the ABC. If there are many decorators, there could be another ABC which provides the common composition handling and function call forwarding that the decorators need.
Explicitly mentioning the interface sometimes makes it more readable. The MSDN documentation often do that, e.g. showing that List<> implements both ICollection<> and IList<> although IList<> is derived from ICollection<>.
The only advantage I could think of with a derived class explicitly implementing the same interface as its base class is to prohibit the derived class from hiding a member and as a result breaking the interface.
Interfaces specify a contract for behavior, so this only makes sense if you have sufficient behavior (beyond simple property accessors) that a non-Person might want to implement IPerson. For instance, if IPerson could HoldConversation(Stream input, Stream output), then you might have a TuringTestCandidate that implements IPerson, without actually deriving from Person.
In more practical terms, this pattern is typically used when you want to unit test behaviors of some class that depends on the interface and you don't want the overhead or possible interference from changes in the base class. It wouldn't make sense for this simplified example, but is often useful in practice.
In this case, your interface and abstract class are quite redundant, except that the abstract class is fulfilling the method requirement of the interface. I don't see the need for the interface in this case, especially given that there is an abstract class.
If you were to be implementing methods on objects with two arms and two legs -> IThingWithArmsAndLegs::DoTheHokeyPokey() that could be a good use of an interface. Then this interface could be shared among Person : IThingWithArmsAndLegs, and Alien : IThingWithArmsAndLegs.
I am a fan of both in the right situation, Why?
Even if you need just an Interface for some type of IOC/DI, it provides no common functionality. You can do this to Inject and have the base functionality covered through a common abstract base class. Then only abstract/virtual methods as needed.
It is oop at it's finest IMHO. Especially in a multi target solution.
I will make my Interfaces one time for all devices, then for each device create an Abstract Class that covers all the same common functionality common to that device type.
Just for the sake of argument you could have common functionality in the abstract Person base class that not everything implementing the interface IPerson needs to reduce duplicate code. At the same time you could have some routines that expect an IPerson to perform some common logic.
Having said that, I wouldn't recommend this practice this at all.
To me it looks bad specify Person and IPerson in the declaration of CoalMiner. I would just derive it from Person. The structur interface -> abstract class -> concrete class is fine with me, but overkill in most situations. I use it sometimes if most of the classes implementing the interface share a lot of code. So deriving from the abstract class is the default case for the 95% simple cases, but I would like to keep the option to have completly independent implementation of the interface.
Interfaces tend to be used a lot in Dependency Injection scenarios because they are considered "light weight" dependencies. Using this approach you tend to have interfaces defining a lot of things, and often end up with abstract classes that implement the interface to provide the base implementation of some or all of the interface members.
I tend to think this is a little extreme, particularly in the example you provided where the abstract class does not provide anything beyond the properties. I have to say I've been guilty of this myself at times, generally using the excuse that the interface makes it more "testable", and is friendlier to my IoC container of choice. I've been trying to reduce the interface bloat in my code recently that comes from a general mentality that loose-coupling via interfaces are required for proper Dependency Injection, realizing that there is a point where things just become silly.
While there is no NEED for CoalMiner to have the IPerson interface, I know some people prefer that so it is obvious that the type implements the interface. That being said, I don't this it is very useful like that.
Interfaces to define nouns are very common in enterprise systems where you may need to support multiple data access layers (DAL) because your system deals with multiple other systems. In this case you might have the following abstract classes
public interface ICustomer {}
public abstract class SapEntity {}
public abstract class NHibernateEntity {}
public class SapCustomer : SapEntity, ICustomer {}
public class NHibernateCustomer : NHibernateEntity, ICustomer {}
public class CustomerProcessor
{
public ICustomer GetCustomer(int customerID)
{
// business logic here
}
}
I find I often need to use both with generic base classes. Usually at some point I need to pass a reference to the open class generic base class which unfortunately you can't do in C#, so I create a non-generic interface.
I can see the point of having both the interface and abstract class (the interface defines the contract, and the abstract class can have a partial implementation that derived classes can share).
However, specifying both the parent class and the interface in the derived class is redundant (It's already implied because the abstract class must implement the interface or it won't compile).
This pattern might just be there as a coding standard so that it is obvious to other programmers when looking at the concrete class that its ancestors implement that interface.
None, if you extend the same interface twice, it's only used the first time. You can delete the 2nd IPerson and your code will still run fine.

Abstract classes vs Interfaces

I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).

Categories