Custom attributes on interfaces or the classes that implement them? - c#

When employing custom attributes to store meta-data, is it best to decorate the interface, or the class that implements the interface, assuming that any class that implements the interface would have the same data in the attribute?
Update: Basically i'm writing a custom data storage mechanism for a project, and the objects represent the various tables being stored. The custom attribute is used to designate which table in the dataset is used to store the objects of that class, and also to identify which tables are involved in a n:m relationship.
So if i put the attributes on the interface, is this a clearer approach, or does it clutter the interface and make accessing the data itself more cumbersome?

It depends on the scenario. WCF, for example, decorates interfaces for the operation contracts.
However, if you are going to be talking about objects (rather than the interface itself), note that it can be painful for calling code to get hold of interface metadata, especially if the class uses explicit interface implementation.
It would be more common to decorate the class, but that isn't quite the same question ;-p
If the attribute really is specific to the interface (not the instances), then fine - decorate the interface and talk about typeof(IFoo) etc. But if you expect code to be able to set per-type values for the attributes, it will have to be at the class level.
What is the scenario?

Well it depends on whether or not the interface has anything to do with the metadata.
interface IRunnable
{
void Run();
}
class Test : IRunnable
{
public void Run() { }
}
In this example it would make sense to put the attributes on the interface if they pertain to the intent of the interface. If the attributes are applicable across all implementations then put the attributes on the interface.
However if the attributes have nothing to do with the "runnability" (with "runnability" pertaining to IRunnable not the CLR) of the class then put the attributes on the class.

Related

Can interface implementations be restricted to an assembly?

I can restrict C# class inheritance to the assembly through internal or private protected constructors. But is something similar possible with interfaces?
Why I want this?
I try to create a framework where specific interfaces exist. For simplicity I call them IInput, IOutput and IInAndOut. The latter inherits the other two.
Those can be used in several places in the framework and there are many implementations provided by the framework as well. Now I want to prevent the user from providing his own implementation. He should only be able to use existing implementations or derive from more specialized classes which already implement the interface.
I could do this with abstract classes instead which have private protected ctors but this won't allow to inherit two other abstract classes.
So I need something like a sealed or use-only interface which can only be implemented in my own assembly.
Is there something like this in C#?
For the users of the framework I would suggest to offer classes where the specific IO methods are implemented. To prevent the users from overriding these methods, they can be marked as sealed, but the classes may be used as base classes for new derived classes.
For the developers of the framework you can use interfaces. In this case I would suggest to declare the interfaces as internal since you don't want the framework's users to implement the interfaces and, consequently, they don't need to see the interfaces. Currently (since C# 8.0), interfaces can contain implementations of some or all methods if this is convenient in the project.
Another option for the framework developers is to offer abstract classes, where the specific IO methods are marked as abstract. Also in this case a class can contain an implementation of a method, which would not be marked as abstract, but rather as virtual. Abstract classes have an advantage over interfaces that they enforce a more rigid structure of project components.
Yes you can make a public interface which can only be implemented internally but it requires a little work around as there is no keyword for this.
//Your framework class implementing interface that is publicly accessible but cannot be implemented outside of your framework assembly.
public class FrameworkClass : IFrameworkOnlyInterface
{
NotImplementable IFrameworkOnlyInterface.CannotBeImplemented()
{
return null;
}
}
//Your interface that will be visible and accessible for user of your framework but cannot be implemented in outside assemblies.
public interface IFrameworkOnlyInterface
{
//A throw-away internal method returning internal type to dissalow implementation from outside of this assembly.
internal NotImplementable CannotBeImplemented();
}
//Internal class used as a throw-away type to dissalow implementation of public interface outside of your assembly.
internal class NotImplementable
{
}
Users of your framework will be able to derive from your FrameworkClass and use it as normal, they will also be able to cast it to IFrameworkOnlyInterface and use its methods apart from CannotBeImplemented() method or any other method you mark as internal.
If you do not want users to access IFrameworkOnlyInterface at all then all you have to do is mark the IFrameworkOnlyInterface as internal.

interfaces to fix inheritence mess?

I'm working on a project with the following (very simplified) structure:
BaseClass
SubClassA : BaseClass
SubClassB : BaseClass
There is a UI (with a lot of logic) which uses SubClassA, and then saves it to another component which takes BaseClass as a parameter but immediately casts the argument to SubClassB. This fails as the UI is passing in SubClassA.
UI:
MyComponent.Save(subClassA)
Component:
Save(BaseClass baseClass)
{
SubClassB subClassB = (SubClassB)baseClass;
...
the current implementation creates an instance of SubClassB in the UI and pass that across - but it leads to lots of code such as
SubClassB.Property1 = SubClassA.Property1a
I'm contemplating creating a common interface which the 2 sub classes would implement. It would be a lot of work but slowly I think I could flatten the current very deep hierarchy. Reworking either the UI or the component to use the other sub type would be just as much work as the structures are different (though many fields map). Is the interface approach the right way to go? I feel there might be something I'm missing.
If SubclassA and SubclassB are related only by their ability to Save, then yes, BaseClass would be better as an interface that both sub-classes implement.
It won't solve your immediate problem straight away: the component casting from base class to (the wrong) derived class. It looks like there could be several levels of refactoring to do here. Patching up the code so that the component casting to a SubclassA by making one for it to use is wasteful, I think. Changing the component so it can operate on a single common type would be a big win there.
Flattening a deep hierarchy would bring lots of other benefits, too - like making it simpler. If there end up being a few interfaces that they all implement, that's not necessarily a bad thing. Beware of lots of interface types hunting in packs, however.
In short, reworking both the UI and the component - and any other code, too - to work in terms of just a small number of interfaces, with no knowledge of the implementing classes, will pay dividends.
From a consumer standpoint, interfaces can do almost everything that abstract classes can do (the main exceptions being that a class can expose a field as a byref, while interfaces have no means of doing so, and that static members associated with a class can be grouped under the class name, static members related to an interface must be grouped under a different name). Except in those rare cases where it's necessary to expose a field as a byref, the primary advantage of an abstract class comes on the side of the implementation. All of the functionality associated with an interface must be provided separately in every class which implements it, even when such functionality is common to 99% of the classes which implement it. By contrast, if 99% of the concrete classes derived from an abstract class will implement a particular method the same way, it's possible for the abstract class to define that method once and let derived classes inherit it without having to pay it any heed whatsoever. Such an advantage can be nice, but there's a major catch: a class can only inherit functionality from one other class. Since interfaces don't include any functionality, they can be inherited from any number of other classes.
When one is defining an abstract class, I would suggest that one should in many cases also define an interface which includes the same public functionality (which the abstract class should implement), and avoid using variables or parameters of the abstract class type. This will allow implementations which can inherit from the abstract class to achieve the ease-of-implementation benefits that would come from doing so, but will also make it possible to define implementations which inherit from something else. Writing an implementation which inherits from some other type would be more work, but if code never uses the abstract-class type in variable, field, or parameter declarations, code which uses derivatives of the abstract class would work just as well with interface implementations that don't.
Why not make a Save() virtual within the base class - it seems like a better option. That way, if you have any common save functionality, you can use it and also give it other forms in derived classes - known as polymorphism.
class BaseClass
{
public virtual void Save()
{
//Use this keyword
}
}
class B : BaseClass
{
public override void Save()
{
base.Save();
}
}

How is polymorphysm look like by using Interfaces?

I don't get the connection of Interfaces To polymorphism.
Polymorphism for me is about executing a method in a different way for some different concrete classes using abstract methods or virtual methods+ overriding and therefore this is only linked to inheritance in my vision, but how do you override methods With Interfaces??
How do you use Interfaces for doing same method in different ways and giving the object to decide what to do according to its concrete type?
Thanks
As stated by Andreas Hartl in his article on Inheritance Vs. Interfaces:
Many high-level languages support inheritance and interfaces, and for
someone new to the concepts, it's sometimes not clear which one to
choose. Although languages differ in their exact handling of
inheritance and interfaces, the basics are usually the same, so this
tip should be valid for most languages.
Inheritance means that we derive one class (the derived class) from
another class (the base class). The derived class is an extension of
the base class. It contains all the features (methods and data
members) of the base class, can extend it with new features, and can
reimplement virtual methods of the base class. Some languages, like
C++, support multiple inheritance, where a derived class can have
multiple base classes, but usually inheritance is restricted to a
single base class.
Interfaces can usually only define methods and no data members (but C#
for example allows data members in the form of properties within
interfaces), and a class can always implement multiple interfaces. An
interface contains only method definitions without implementations,
and a class that implements an interface supplies the implementation.
So, using inheritance, you write a base class with method
implementations, and when you derive a class from it, this class will
inherit everything from the base class, and is immediately able to use
its features. An interface on the other hand is just a contract of
method signatures, and a class that wants to implement an interface is
forced to supply the implementations for all methods of the interface.
So when do you use which? In some cases, the language already dictates
what you use: if you need your class to have multiple 'parents', you
cannot use inheritance in languages that don't support multiple
inheritance. And if you want to reuse a library object, you have to
use the fitting concept, depending on if that library object is a
class or an interface.
But which to use if you are free to choose? Basically, base classes
describe and implement common behavior of related types, while
interfaces describe functionality that unrelated types can implement.
Inheritance describes 'is a' relationships, interfaces describe
'behaves like' relationships. For example, say that you are writing a
flight simulator. Your basic entity, which you will for example store
in a list, will be 'Airplane'. Your concrete types will be 'Concorde'
and 'Phantom'. So how should you model the three types? Concorde and
Phantom are related, they both are airplanes and share data, like
'Weight' or 'MaxSpeed' and functionality, like 'Accelerate', so we can
model them with inheritance. 'Airplane' will be the base class with
common data and methods, and 'Concorde' and 'Phantom' will derive from
'Airplane'. We could say that both are specialized airplanes, which is
why it's often said that inheritance means specialization. Now assume
that we also add a class 'Pilot' to our program, and we want to give
the user the ability to save the game and load it later. So when he
saves the game, we need to save the state of all Aircrafts and the
state of all Pilots. And we want to do this in one function that takes
just a list of all saveable objects. So how do we model this? To
answer this, we must take a look at the different types we want to
save. Pilots and Airplanes. It's obvious that they are not related at
all. They share no common data and no common functionality. We can see
that writing a base class 'Saveable' and derive both Pilot and
Airplane from it would make little sense, since no code in Saveable
could be reused by Airplane or Pilot, since both have no common
properties. In this case, an interface is the best solution. We can
write an interface 'ISaveable' with a method Save(). Pilot could then
implement ISaveable.Save() by saving his name, while Airplane could
save its current speed and coordinates.
As you can see, a clear image of the relationship between classes
often makes the choice clear: Use inheritance for related types, where
each derived class 'is a' base class. Use interfaces for unrelated
types which have some common functionality.
Here are some more points to consider with inheritance and interfaces:
Interfaces are fixed. When you change an interface, you have to change every class implementing that interface. But when you change a
base class, every derived class will gain the new functionality, which
can both be good (if you make a bugfix in some base class method
implementation, a derived class using that method will gain the bugfix
without you needing to change it) or bad (if a change in the baseclass
introduces a new bug, all derived classes using the method will be
bugged too).
Interfaces are usually more flexible, since in most languages you can only derive from one class, but implement many interfaces
Interfaces help to protect internal classes: Assume class A has an internal object b of class B. When a method in A returns a pointer or
reference to b, the code that called this method now has access to the
whole object b, which can be dangerous if A only wants to expose
certain members of b. This problem can be solved if you create an
interface I with just the members which are safe to expose. When B
implements this interface, and your method in A returns b via an I
pointer or reference, the outside code can only do what you allow
through the interface.
Polymorphism as a concept does not require inheritance, although in many languages inheritance is the only way to achieve it. Some languages, like smalltalk allow you to polymorphically use any type that implements the same set of members and properties. If it looks like a duck, quacks like a duck, and walks like a duck, you can treat it like a duck.
Polymorphism is simply the ability to treat one object as another object, by providing the same way to access and use it as the original object. This is best illustrated by the Liskov Substitution Principle. This is called the "Interface" or sometimes "Contract", because it defines a "signature" that another object can use to do interesting things to the object.
in C#, you can inherit from interfaces or other (non-sealed) classes. The difference is that an interface does not provide any actual storage or methods (only their "signature"), it is merely a definition. You can't instantiate an interface, you can only instantiate an object that implements an interface.
Classes implement an interface (IDisposable, for instance) in the same way you build a house based on blue prints. If you build two houses with the same blueprints, then each house has the exact same "interface", they may have different color paint, or carpeting, but they function in exactly the same way, yet they are two distinctly different houses, with many differences in how various things might function.
When it comes to C#, just know that an interface says what properties or members an object that implements it MUST have. Likewise, in C#, a big difference is that you can inherit multiple interfaces but only ever a single class. (ie public class Test : BaseClass, IDisposable, ITest, IFooBar)
consider this...
public int SomeMethod(SomeBaseClass object)
{
// Pass in a descendant classe that implements / overrides some method in SomebaseClass
}
public int SomeMethod(ISomeInterface intf)
{
// pass in concrete classes that implement some ISomeInterface function
}
This is the basic essence of polymorphic behavior, a common contract, implemented specifically by a specialist class.

C# - What should I use, an Interface, Abstract class, or Both?

So, hypothetically, I'm building some sort of real estate application in C#. For each type of property, I'm going to create a class such as ResidentialProperty and CommercialProperty. These two classes as well as all other property classes will share some common properties, such as Id, Title, Description, and Address information.
What I would like to be able to do is:
a) return a collection of objects that contain just the basic information
b) be able to either call a method such as GetProperty(id) which will create and return either a ResidentialProperty or CommercialProperty, or call GetProperties() which will return a collection of one or the other, or both.
So with that said, it would probably make sense to create an abstract class called BasicProperty (or PropertyBase) which contains all of the common attributes, and have the ResidentialProperty and CommercialProperty extend from it. This would take care of problem #1, as I could create a method that returns a collection of BasicProperties.
But for #2, being able to return either one property type or the other, I would need an Interface (IProperty), and have the Residential and Commercial classes inherit from it, and then have the GetProperty(id) and GetProperties() return an IProperty object (or because they inherit from IProperty, can I return them as is and not as the Interface?)?
Now if I should use an Interface, what do I do with the BasicProperty class?
- Do I leave it as an abstract and implement the Interface? Or
- Do I leave it as an abstract and all 3 classes implement the Interface? Or
- Do I not create it as an abstract, put all of the basic information into the Interface, and the BasicProperty, ResidentialProperty and CommercialProperty all implement the Interface?
Thanks in advance,
Carl J.
While I feel that defining an interface to begin with is almost always a good idea, just because it helps your code to be flexible in the future, it sounds like in this case you don't actually need to do that. Your GetProperty and GetProperties methods can use your abstract base class as a return value.
Think of it like this: What if I had a method called GetShape? It would presumably return a Shape, right? Let's say Shape is an abstract base class, and some derived classes are Triangle, Square, Circle, etc.
But a triangle is a shape, a square is a shape, and so on--each of these happens to be more than just a shape, but they are shapes nonetheless. So if I say "give me a shape" and you hand me a square, you're doing just as I asked. No funny business there.
This is one of the core underlying principles of OOP: an instance of a derived class is an instance of its base class; it's just also more than that.
From what I can gather, you are talking about two different things here.
Class structure
Data Access of those classes
You are correct in thinking that you should create an abstract class to contain the common properties, that's what inheritance is for :) (among other things)
But I dont see why you can't create a data access class that has a method GetProperty(id) that specifies a return type of PropertyBase
i.e.
public PropertyBase GetProperty(long id)
in the implementation of GetProperty you can construct a ResidentialProperty or CommercialProperty (based on what ever business/database logic you want) then return it, c# allows you to do that.
Perhaps I miss-understood you?
HTH
EDIT::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
class DataAccessLayer
{
public PropertyBase GetSomething(int id)
{
if (id > 10)
return new CommercialProperty();
else
return new ResidentialProperty();
}
}
class PropertyBase { }
class ResidentialProperty : PropertyBase { }
class CommercialProperty : PropertyBase { }
}
An abstract class is used to provide common behaviour. An interface is used to provide a specific set of methods and properties, regardless of how they behave.
If your ResidentialProperty and CommercialProperty provide some common behaviour then it probably makes sense to implement this behaviour in an abstract class and have each of them inherit from this class. Presumably they also will have some custom behaviour ,otherwise there is no need to sub-class, it would then be sufficient just to have a PropertyType property to describe which type of Property the instance is.
You can then provide as many interfaces as you feel would be useful, IPropertyBase, IResidentialProperty and/or ICommercialProperty. It really depends on whether you expect this library to be used a base for other implementations which may have the same interface as one or more of your classes, but not the same behaviour as your base abstract class. The other benefit of exposing interfaces which represent your types is easier mocking for unit testing.
It's not really possible to answer this question absolutely because it really depends on how your objects are likely to be used, but I hope this answer provides you with a useful guideline.
It is my opinion that you should avoid using abstract classes unless it absolutely makes sense you should.
A lot of the common behaviour can be given to your entities through aggregation, using components and you can publicise this behaviour through the use of interfaces.
The reason I tend to go down this route, is that once you have an abstract base class, you're tied to using it, as you can't have multiple inheritance.
Sooner or later, you end up with a situation in which you DO want multiple inheritance and you're screwed.
Not that I'm a hardliner on this, because plenty of our code-base does utilise base abstract classes for the above, but those implement the interfaces and all the code enacting on those classes talk to them through the interfaces, so we can switch out the base classes for something more flexible later if necessary.
A quick not about the difference as I see it. You can always use an abstract base class even when you implement interfaces. Interfaces does not help you avoid code duplication which you should (see the DRY principle) but it doesn't force you to derive from anything special which makes them easier to combine with other base classes or interfaces.
An abstract base class on the other hand can remove some duplication and it is easier to change some things in the base without touching the derived classes. The latter is very nice when you implement a class library that others use. If you change things in interfaces in a library, all implementations of that interface needs to change! This might be a very small problem if you only implement an application with a small group of developers. But as other has said, a base class forces you to derive from it and then you cannot derive from something else if that need should appear.
Don't call your base class or interface BasicProperty or PropertyBase, just call it Property. You will not have both a Property and a BasicProperty, will you? You will act with Property classes or interfaces.
An abstract class is almost the same as an interface with the difference that the abstract class can store state in field variables. When your Properties have data like the address that is stored an abstract class with a field is one way to do that.
Now the subclassing of a class is one of the picture book examples of OOD, but there are other ways of differentiating objects than that, look at the decorator and behavior patterns. You should subclass only if you need to override methods of the base class. Have a look at this for example.

Interface or abstract class?

For my new Pet-Project I have a question for design, that is decided already, but I want some other opinions on that too.
I have two classes (simplified):
class MyObject
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
}
class MyObjectGroup
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
List<MyObject> myobjects {get;set;}
}
Later in the Project MyObjectGroup and MyObject should be used equally. For this I could go two ways:
Create an interface: IObject
Create an abstract class: ObjectBase
I decided to go the way of the interface, that I later in code must not write ObjectBase every time but IObject just for ease - but what are other positives for this way?
And second, what about adding IXmlSerializable to the whole story?
Let the interface inherit from IXmlSerializable or does it have more positives to implement IXmlSerializable in abstract base class?
Generally speaking, the approach I use in this kind of situation is to have both an interface and an abstract class. The interfaces defines, well, the interface. The abstract class is merely a helper.
You really can't go wrong with this approach. Interfaces give you the flexibility to change implementation. Abstract classes give you boilerplate and helper code that you aren't forced to use, which you otherwise would be if your methods were defined in terms of an abstract class explicitly.
These are some of the differences between Interfaces and Abstract classes.
1A. A class may inherit (Implement) one or more interfaces. So in C#, interfaces are used to achieve multiple inheritance.
1B. A class may inherit only one abstract class.
2A. An interface cannot provide any code, just the signature.
2B. An abstract class can provide complete, default code and/or just the details that have to be overridden.
3A. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public.
3B. An abstract class can contain access modifiers for the subs, functions, properties.
4A. Interfaces are used to define the peripheral abilities of a class. For eg. A Ship and a Car can implement a IMovable interface.
4B. An abstract class defines the core identity of a class and there it is used for objects.
5A. If various implementations only share method signatures then it is better to use Interfaces.
5B. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
6A. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
6B. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
7A. An interface can not have fields defined.
7B. An abstract class can have fields and constants defined.
8A. An interface can not have constructor.
8B. An abstract class can have default constructors implemented.
9A. An interface can only inherit from other interfaces.
9B. An abstract class can inherit from interfaces, abstract class, or even class.
The interface would be my default until there is a reason to use a base class, as it makes fewer decisions for us.
I wouldn't involve IXmlSerializable unless I had to though; it is a messy, tricky interface that is often a cause of woe.
What exactly are your serialization requirements? There may be better options... however, for many serializers a base-class would be easier than an interface. For example, for XmlSerializer you could have:
[XmlInclude(typeof(MyObject))] // : ObjectBase
[XmlInclude(typeof(MyObjectGroup))] // : ObjectBase
public abstract class ObjectBase { /* */ }
(the exact approach depends on the serializer)
Generally, you should consider interfaces as contracts that some types implement and abstract classes as nodes in inheritance hierarchy that don't exist by themselves (i.e. there is an "is a" relationship between the derived class and the base abstract class). However, in practice, you might need to use interfaces in other cases, like when you need multiple inheritance.
For instance, IXmlSerializable is not an "entity" by itself. It defines a contract that an entity can implement. Interfaces live "outside" the inheritance hierarchy.
An Interface will allow you to define a 'contract' that the object will need to fulfil by delivering properties and methods as described by the interface. You can refer to objects by variables of interface-type which can cause some confusion as to what exactly is being offered.
A base class offers the opportunity to build an inheritance 'tree' where more complex classes (of a common 'type') are built on the foundations of a simpler 'base' classes. The classic and annoying example in OO is normally a base class of 'Shape' and which is inherited by Triangle, Square, etc.
The main point is that with an Interface you need to provide the entire contract with every class that implements it, with an inheritance tree (base classes) you are only changing/adding the properties and methods that are unique to the child class, common properties and methods remain in the base class.
In your example above I'd have the 'MyObjectGroup' object inherit the base 'MyObject' class, nothing to be gained from an interface here that I can see.
There are two thing is in Architect’s mind when designing classes.
Behavior of an object.
object’s implementation.
If an entity has more than one implementation, then separating the behavior of an object from its implementation is one of the key for maintainability and decoupling.
Separation can be achieved by either Abstract class or Interface but which one is the best? Lets take an example to check this.
Lets take a development scenario where things (request, class model, etc) are changing very frequently and you have to deliver certain versions of application.
Initial problem statement : you have to create a “Train” class for Indian railway which has behavior of maxSpeed in 1970 .
1. Business Modeling with abstract class
V 0.0 (Initial problem)
Initial problem statement : you have to create a Train class for Indian railway which has behavior of maxSpeed in 1970 .
public abstract class Train {
public int maxSpeed();
}
V 1.0 (Changed problem 1)
changed problem statement : You have to create a Diesel Train class for Indian railway which has behavior of maxSpeed, in 1975.
public abstract class DieselTrain extends train {
public int maxFuelCapacity ();
}
V 2.0 (Changed problem 2)
chanded problem statement : you have to create a ElectricalTrain class for Indian railway which has behavior of maxSpeed , maxVoltage in 1980.
public abstract class ElectricalTrain extends train {
public int maxvoltage ();
}
V 3.0 (Changed problem 3 )
chanded problem statement : you have to create a HybridTrain (uses both diesel and electrcity) class for Indian railway which has behavior of maxSpeed , maxVoltage,maxVoltage in 1985 .
public abstract class HybridTrain extends ElectricalTrain , DisealTrain {
{ Not possible in java }
}
{here Business modeling with abstract class fails}
2. Business Modeling with interface
Just change abstract word to interface and ……
your Business Modeling with interface will succeeds.
http://javaqna.wordpress.com/2008/08/24/why-the-use-on-interfaces-instead-of-abstract-classes-is-encouraged-in-java-programming/
Interface:
If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.
For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.
–> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.
For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .
Abstract Classes:
–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.
You could actually go with BOTH. ObjectBase saves you the trouble of implementing the common properties more than once and implements IObject for you. Everywhere you use it refer to IObject so you can do testing with mocks later
I'd rather go for base abstract class, because, theoretically (well, it's just one theory, I'm not proving or saying that any other is worse then this) - interfaces should be used, when you want to show, that some object is capable of doing something (like IComparable - you show that whatever implements it, can be compared to something else), whereas when you have 2 instances that just share something common or have 1 logical parent - abstract classes should be used.
You could also go for both approaches, using base class, that will implement an interface, that will explicitly point what your class can do.
Note that you cannot override operators in Interfaces. That is the only real problem with them as far as I'm concerned.
All else being equal, go with the interface. Easier to mock out for unit testing.
But generally, all I use base classes for is when there's some common code that I'd rather put in one place, rather than each instance of the derived class. If it's for something like what you're describing, where the way they're used is the same, but their underlying mechanics are different, an interface sounds more appropriate.
I've been using abstract classes in my projects, but in future projects, I'll use interfaces.
The advantage of "multiple inheritance" is extremely useful.
Having the ability to provide a completely new implementation of the class, both in code, or for testing purposes, is always welcome.
Lastly, if in the future you'll want to have the ability to customize your code by external developers, you don't have to give them your real code - they can just use the interfaces...
If you have function in class,you should use abstact class instead of interface.
In general,an interface is used to be on behalf of a type.
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
The definition of the abstract class may describe code and state, and classes that derive from them may not derive from other classes at the same time. That's what the technical difference is.
Therefore, from the point of view of usage & philosophy, the difference is that by setting up an abstract class, you constrain any other functionality that the objects of that class may implement, and provide those objects with some basic functionality that is common for any such object (which is a kind of constraint, too), while by setting up an interface, you set up no constraints for other functionality and make no real-code provisions for that functionality which you have in mind. Use the abstract classes when you about know everything that objects of this class are supposed to be doing for the benefit of their users. Use the interfaces when the objects might also do something else that you can't even guess by now.

Categories

Resources