Programming against an interface with only one class implementing said interface - c#

I can understand why to program against an interface rather than an implementation. However, in an example like the following (I find this a lot):
public interface ISomething
{
void BlahOne(int foo);
void BlahTwo(string foo);
}
public class BaseSomething : ISomething
{
public void BlahOne(int foo)
{
//impl
}
public void BlahTwo(string foo)
{
//impl
}
}
public class SpecificSomethingOne : BaseSomething
{
public void SpecificOne()
{
//blah
}
}
public class SpecificSomethingTwo : BaseSomething
//and on..
The current example of this is the component based entity system in my game. (I have IComponent, Component, PosComponent, etc).
However, I cannot see a reason to have ISomething. The name may look nicer, but it doesn't seem to have a purpose. I can just return BaseSomething all the time.
Is there a reason to have an interface when you have a single base implementation everything uses? (I can see the use for, say, IComparable or IEnumerable)
EDIT: For a slightly different scenario (yet still related enough to not need a different question), if I assume I have this structure for everything, would there be much difference if I were to use ISomething for parameter types and variables compared to BaseSomething?

I prefer "lazy design" - extract the interface from BaseSomething when you need it. Until then, keep it simple and skip it.
Right now I can think of two reasons for having an interface when there is only one implementation:
There is another mock implementation for unit tests (i.e. there is a second implementation, although not in production code).
The interface and the implementation are defined in different class libraries. E.g. when using the Model-View-Presenter pattern, the view can reside in an .exe project that is dependent on the .dll where the presenter is implemented. Then an IView interface can be put in the .dll and the presenter's reference to the view supplied through dependency injection.

Correct answer to your question would be "It depends".
You can look at it in many different ways and it's all about perspective. When you have a concrete or abstract base class, it means your objects have something in common functionally. And derived objects are inter-related in some way or the other. Interfaces let you confirm to a functional contract only where each object implementing the interface will be responsible for the implementation.
Again, when you program again interfaces, you strictly know the capabilities of the object since it implements the given interface. And you need not worry about how each object functionally implements this.
It'd not be completely wrong, If I say
each of your objects are completely
independent when it comes to
implementing the interface ISomething, given that SpecificSomethingOne and SpecificSomethingTwo do not derive from BaseSomeThing and each implement their own ISomething.
You can refer to this answer on the same matter.

it is not really necessary but it is a better design if you want to extend your program later or you want to implement another Base-Class.
In your case I would not implement the Base-Class. The Interface only is just fine if you dont want to have a default-behaviour. If you want a default-behaviour then just write the Base-Class without an Interface

If your BaseSomething were abstract and you had implementing specific things that provider overloads to abstract methods, the only way to program to them at that point would be to the ISomething interface. However, in the example you showed, there is really no reason for ISomething unless you could have multiple base implementations.

Related

Is it incorrect to use classes (instead of interfaces) to set up plug-in mechanism?

Assume this hypothetical situation:
I have a hierarchy of classes:
public class MyBase : System.Windows.Forms.TreeNode
{
public virtual void Init() {...}
}
Now I want to allow third parties to use MyBase to develop their derived classes like these:
public class Drv1 : MyBase { public override void Init() {...} }
public class Drv2 : MyBase { public override void Init() {...} }
I want my application be able to use Drv1 and Drv2 as plug-ins.
Now, my questions are:
Is it incorrect (or bad practice) to use classes (instead of interfaces) to set up plug-in mechanism?
Did I make a mistake I didn't use interfaces to provide THIRD-PARTIES with an interface? (because I want to persuade others to develop plug-ins for my app)
If answer of question 2 is YES, how could I use interfaces (because MyBase is derived from TreeNode) ? (this answer is critical for me)
Many thanks in advance.
Im using following rules:
If there is any code required in base then go for class.
If you need only structure or you need to "inherit" more than one class, use interfaces.
If you need both, features and multiple inheritance use both.
Its really depends what you do with that classes later on.
In your case you should be using base class as virtual method has some code in it, and you inherit from class that is 3rd party for you.
But once your business classes should use different implementation of that class then its worth of adding interfaces and use it in IoC or something.
I think going for Interfaces for only sake of it is not correct approach.
Is it incorrect (or bad practice) to use classes (instead of interfaces) to set up plug-in mechanism?
Neither C# or .NET has anything that labels this as incorrect. They describe under what circumstances your code will continue to work, and when it won't. Bad practice is a matter of opinion, but there are advantages and disadvantages to both approaches.
If answer of question 2 is YES, how could I use interfaces (because MyBase is derived from TreeNode) ? (this answer is critical for me)
If your callers need to provide a type that is derived from TreeNode, and you wish to use an interface, then you can.
public interface IMyInterface {
void Init() {...}
}
You cannot require classes implementing IMyInterface to derive from TreeNode, but you do not need to: you can ensure that the only way this gets exposed to your own application is via a generic registration method, where the generic type constraints do force the type to both derive from TreeNode and implement this interface:
public void RegisterTreeNode<T>() where T : TreeNode, IMyInterface {...}
If plugins are able to call RegisterTreeNode<Drv1>(), you're assured at compile time that it's going to match your requirements. You may of course use a different method signature, possibly one that deals with individual instances of the TreeNode class, it's the type constraints that are key here. If a caller attempts
class X : IMyInterface { public void Init() {...} }
and then
RegisterTreeNode<X>();
the compiler will simply reject this. The plugin may create instances of this X itself, but if your application never sees them, they cannot cause any harm.
Then third parties can do:
public class Drv1 : TreeNode, IMyInterface { ... }
public class Drv2 : TreeNode, IMyInterface { ... }
or even
public class Drv3 : SuperTreeNode, IMyInterface { ... }
where SuperTreeNode is derived from the standard TreeNode.
This is probably the main benefit of using an interface here: it's compatible with existing classes which provide additional functionality on top of the standard TreeNode.
This cuts both ways: the main benefit of using a common base class here, rather than an interface, would be that your own code can provide additional functionality.
P.S.: Depending on what you're after, it may also be possible to decouple this, to make your base class / interface responsible for creating TreeNode objects, rather than deriving from TreeNode. The general rule that favours this approach is called "composition over inheritance", and worth reading up on. It may or may not be a good fit for your particular use case.

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

Difference between Interface and Abstract class in terms of Decoupling?

As we know there are basically two important difference between Interface and Abstract class.
We can have function definitions in abstract class. This is advantageous when we want to add a function in a class without need to track down it's all implementations.
We can have multiple interface implementation.
I just came to know that we can differentiate between them in terms of Decoupling?
Your comments...
Also if you can you provide a very basic link that explains the Decoupling for Interface and Abstract class ?
We normally use Business Logic Layer, Data Access Layer(contains abstract functions) and DataAccess.SqlServer Layer. Right? Despite of the fact that we aware of the Business needs, why are we creating Data Access Layer(contains abstract functions), Why can't Business Logic layer directly access DataAccess.SqlServer Layer?
Decoupling
In programming and design, this is generally the act of making code which is re-usable with as few dependencies as possible.
Factory Pattern In This Context
When using the Factory Pattern, you have a centralized factory which can create objects without necessarily defining them itself. That would be up to the object's definition.
Abstract and Interface
Interface
Defining an interface is best practice, as it allows for a light weight type to be used for inference, and also provides a blueprint which all inheriting classes must abide by. For example, IDisposable must implement the Dispose method. Note that this is decoupled from the interface, as each class inheriting IDisposable will define its own function of the Dispose method.
Abstract
Abstract is similar to interface in that it is used for inheritance and inference, but it contains definitions which all classes will inherit. Something to the extent of every automobile will have an engine so a good abstract class for automobile could include a predefined set of methods for an engine.
Edit
Explanation
Here you will see a simple example of inheritance using an interface and an abstract class. The decoupling occurs when the interface is inherited by an abstract class and then it's methods are customized. This allows for a class to inherit the abstract class and still have the same type as the interface. The advantage is that the class inheriting the abstract class can be used when the expected type is the original interface.
Decoupling
That advantage allows for any implementation to be used which conforms to the expected interface. As such, many different overloads can be written and passed in. Here is an example of one.
Example
Interface Definition
public interface IReady
{
bool ComputeReadiness();
}
Inheritance
public abstract class WidgetExample : IReady
{
public int WidgetCount { get; set; }
public int WidgetTarget { get; set; }
public bool WidgetsReady { get; set; }
public WidgetExample()
{
WidgetCount = 3;
WidgetTarget = 45;
}
public bool ComputeReadiness()
{
if (WidgetCount < WidgetTarget)
{
WidgetsReady = false;
}
return WidgetsReady;
}
}
public class Foo : WidgetExample
{
public Foo()
{
this.WidgetTarget = 2;
}
}
public class Bar : IReady
{
public bool ComputeReadiness()
{
return true;
}
}
Decoupling
public class UsesIReady
{
public bool Start { get; set; }
public List<string> WidgetNames { get; set; }
//Here is the decoupling. Note that any object passed
//in with type IReady will be accepted in this method
public void BeginWork(IReady readiness)
{
if (readiness.ComputeReadiness())
{
Start = true;
Work();
}
}
private void Work()
{
foreach( var name in WidgetNames )
{
//todo: build name
}
}
}
Polymorphism
public class Main
{
public Main()
{
//Notice that either one of these implementations
//is accepted by BeginWork
//Foo uses the abstract class
IReady example = new Foo();
UsesIReady workExample = new UsesIReady();
workExample.BeginWork(example);
//Bar uses the interface
IReady sample = new Bar();
UsesIReady workSample = new UsesIReady();
workSample.BeginWork(sample);
}
}
I've been looking through the answers, and they all seem a little complicated for the question. So here is my (hopefully) simpler answer.
Interface should be used when none of the implementation details are available to the current scope of the code.
Abstracts should be used when some of the implementation details are available to you
And, for completeness, when all of the implementation details are available you should be using classes.
In terms of decoupling, while I somewhat agree with Shelakel, for the purposes of this question, and stating fully decoupled design practices, I would suggest the following:
Always use Interfaces to define external behaviour.
When you have some of the implementation details available, use
abstract classes to define them, but implement the interfaces on
the abstract classes, and inherit from those classes in turn.
This ensures that later if you need to change some obscure implementation detail in a new implementation you are able to do so without modifying the existing abstract class, and are also able to group different implementation types into different abstract classes.
EDIT: I forgot to include the link :)
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Abstract classes and interfaces are not MUTUALLY EXCLUSIVE choices. I often define both an Interface and an abstract class that implements that interface.
The interface ensure the maximum decoupling because it doesnt force your class to belong to a specific inheritance hierarchy, so your class may inherit from whichever other class. In other terms any class can inherit from an Interface, while classes that already inherits from other classes cannot inherit from an abstract class.
On the other side in an abstract class you can factor out code that is common to all implementations, while with Interfaces you are forced to implement everything from the scratch.
As a conclusion, often the best solution is using BOTH an abstract class and an Interface, so one can move from re-using the common code contained in the abstract class, if possible, to re-implementing the interface from the scratch, if needed.
Decoupling for the sake of decoupling is a futile exercise.
Interfaces are meant to be used for integration where the specifics aren't required to be known to be of use (ex. SendEmail()). Common uses include components, services, repositories and as markers for IOC and generic implementations.
Extension methods with generic type constraints that include interfaces allow functionality similar to traits found in Scala with similar composability.
public interface IHasQuantity { double Quantity { get; } }
public interface IHasPrice { decimal PricePerUnit { get; } }
public static class TraitExtensions
{
public static decimal CalculateTotalPrice<T>(this T instance)
where T : class, IHasPrice, IHasQuantity
{
return (decimal)instance.Quantity * instance.PricePerQuantity;
}
}
In my opinion, abstract classes and class inheritance is overused.
SOLID design principles teach us that Liskov's substitution principle implies that class inheritance should only be used if the inherited class is substitutable for the ancestor. This means that all methods should be implemented (no throw new NotImplementedExeption()) and should behave as expected.
I personally have found class inheritance useful in the case of the Template Method pattern as well as for state machines. Design patterns such as the builder pattern are in most cases more useful than deep chains of inheritance.
Now back to your question; interfaces should be used most if not all of the time. Class inheritance should be used internally and only externally for purposes of definition, whereafter an interface should be used for interaction and the concrete implementation provided via a factory or to be injected via an IOC container.
Ideally when using external libraries, an interface should be created and an adapter implemented to expose only the functionality required. Most of these components allow to be configured beforehand or at runtime to be resolved via an IOC container.
In terms of decoupling, it is important to decouple the application from its implementations (especially external dependencies) to minimize the reasons to change.
I hope that my explanation points you in the right direction. Remember that it's preferred to refactor working implementations and thereafter interfaces are defined to expose functionality.
I'm not going to discuss what are the pros/cons of these two constructs in general, as there are enough resources on that.
However, In terms of 'decoupling' a component from another, interface inheritance is much better than abstract classes, or class inheritance in general (In fact I don't think being abstract or not does not make much difference in terms of decoupling as all abstract does is prevent the class being instantiated without a concrete implementation).
Reason for above argument is, interfaces allow you to narrow down the exposure to absolute minimum of what required by the 'dependent component', if it requires a single method interface can easily do that, or even be a marker interface without any method. This might be difficult with a base class (abstract or concrete) as it should implement all the 'common' functionality for that base. Because of this a component dependent on the 'base type' will automatically 'see' all the common functionality even it does not need them for it's purposes.
Interfaces also gives you the best flexibility as even classes inheriting from bases which have nothing in common, can still implement an interface, and be used by the component expecting that interface. Good example of this is IDisposable interface.
So, my conclusion is for decoupling concern have all your components depend on interfaces than base types, and if you find most of your classes implementing that interface has a common implementation then have a base class implementing that interface and inherit other classes from that base.
The core difference is this:
Interfaces expose zero or more method signatures which all descendants must in turn implement (otherwise code won't even compile).
Interface-exposed methods can either be implemented implicitly (every type derived from the interface has access to them) or explicitely (methods can be accessed only if you typecast the object to the interface type itself). More details and an example can be found in this question.
Abstract classes expose zero or more full-fledged methods, which descendants can either use or override, providing their own implementation. This approach allows you to define a customizable, "default" behavior. Abstract classes allows you to easily add new methods with no issues (NotImplementedException really shines when adding methods to abstract classes), whereas adding a method to an interface requires you to modify all the classes implementing it.
The final point is, that a class can implement more than one interface simultaneously.
Some real-world example might be:
A hard drive which provides both USB and LAN ports is a good demonstration of multiple interface inheritance
A Laptop which has a LED marked "bluetooth" but no bluetooth hardware on board is a good analogy of the concept of not implementing an abstract method (you have the LED, you have the little B symbol, but there's nothing under the roof).
Edit 1
Here's a MSDN link explaining how to choose between interface and classes.
Defining a contract using an abstract class means that your implementers must inherit from this abstract class. Since C# doesn't support multiple inheritance, these implementers will not be able to have an alternate class hierarchy, which can be pretty limiting for some. In other words, an abstract class basically otherwise robs the implementer of the class hierarchy feature, which is often needed to get or use some other capabilities (of a framework or class library).
Defining a contract using an interface leaves the class hierarchy free for your implementers to use any way they see fit, in other words, providing much more freedom of implementation.
From a perspective of evaluation criteria, when we talk about coupling here we can speak to concerns of three separable authors, the client using (calling) the API/contract, the definer of the API/contract, and the implementer of the API/contract; we can speak to freedom (the fewer restrictions, the better), encapsulation (the less awareness necessary, the better), and resilience in the face of change.
I would offer that an interface results in looser coupling than an abstract class, in particular, between the definer and the implementer, due to higher freedom offered the implementer.
On the other hand, when it comes to versioning, you can at least add another method to the abstract class without necessarily requiring updates to subclass implementations, provided the added method has an implementation in the abstract class. Versioning interfaces across DLL boundaries usually means adding another interface, much more complex to roll out. (Of course, this is not a concern if you can refactor all the implementations together (say, because they're all in the same DLL)).
The best way to understand and remember difference between interface and abstract class, it's to remember that abstract class is a normal class and you can do everything with abstract class that you can do with the normal class with two exceptions.
You can't instantiate an abstract class
You can have abstract method only in abstract class
Coding to interface provides reusability and polymorphism.As far as class implements interface,the interface or abstract class can be passed to parameter instead of class that implements the interface.Urs common technical problem is handled vis designing interface and abstract class and implementing it and giving subclass the specific functionality implementation.Imagine its like framework.Framework define interface and abstract class and implement it that is common to all.And those that are abstract is implemented by client according to its own requirement.
public interface Polymorphism{
void run();
Void Bark();
Energy getEnergy(Polymorphism test);
Public abstract class EnergySynthesis implements Polymorphism{
abstract void Energy();
Void Bark(){
getEnergy(){
}
void run(){
getEnergy();
}public EnegyGeneartion extends EnergySynthesis {
Energy getEnergy(Polymorphism test){
return new Energy( test);
}
MainClass{
EnegyGeneartion test=new EnegyGeneartion ();
test.getEnergy(test);
test.Bark()
.
.
.
.
.
//here in Energy getEnergy(Polymorphism test) any class can be passed as parameter that implemets interface

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.

Using explicit interfaces to ensure programming against an interface

I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.
Example:
public interface ICut
{
void Cut();
}
public class Knife : ICut
{
void ICut.Cut()
{
//Cut Something
}
}
And to use the Knife object:
ICut obj = new Knife();
obj.Cut();
Would you recommend this method of interface implementation? Why or why not?
EDIT:
Also, given that I am using an explicit interface the following would NOT work.
Knife obj = new Knife();
obj.Cut();
To quote GoF chapter 1:
"Program to an interface, not an implementation".
"Favor object composition over class inheritance".
As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.
ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)
ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?
I've only used it in scenarios where I want to restrict access to certain methods.
public interface IWriter
{
void Write(string message);
}
public interface IReader
{
string Read();
}
public class MessageLog : IReader, IWriter
{
public string Read()
{
// Implementation
return "";
}
void IWriter.Write(string message)
{
// Implementation
}
}
public class Foo
{
readonly MessageLog _messageLog;
IWriter _messageWriter;
public Foo()
{
_messageLog = new MessageLog();
_messageWriter = _messageLog;
}
public IReader Messages
{
get { return _messageLog; }
}
}
Now Foo can write messages to it's message log using _messageWriter, but clients can only read. This is especially beneficial in a scenario where your classes are ComVisible. Your client can't cast to the Writer type and alter the information inside the message log.
Yes. And not just for testing. It makes sense to factor common behaviour into an interface (or abstract class); that way you can make use of polymorphism.
public class Sword: ICut
{
void ICut.Cut()
{
//Cut Something
}
}
Factory could return a type of sharp implement!:
ICut obj = SharpImplementFactory();
obj.Cut();
This is a bad idea because their usage breaks polymorphism. The type of the reference used should NOT vary the behavior of the object. If you want to ensure loose coupling, make the classes internal and use a DI technology (such as Spring.Net).
There are no doubt certain advantages to forcing the users of your code to cast your objects to the interface types you want them to be using.
But, on the whole, programming to an interface is a methodology or process issue. Programming to an interface is not going to be achieved merely by making your code annoying to the user.
Using interfaces in this method does not, in and of itself, lead to decoupled code. If this is all you do, it just adds another layer of obfuscation and probably makes this more confusing later on.
However, if you combine interface based programming with Inversion of Control and Dependency Injection, then you are really getting somewhere. You can also make use of Mock Objects for Unit Testing with this type of setup if you are into Test Driven Development.
However, IOC, DI and TDD are all major topics in and of themselves, and entire books have been written on each of those subjects. Hopefully this will give you a jumping off point of things you can research.
Well there is an organizational advantage. You can encapsulate your ICuttingSurface, ICut and related functionality into an Assembly that is self-contained and unit testable. Any implementations of the ICut interface are easily Mockable and can be made to be dependant upon only the ICut interface and not actual implementations which makes for a more modular and clean system.
Also this helps keep the inheritance more simplified and gives you more flexibility to use polymoprhism.
Allowing only callers expecting to explicit interface type ensures methods are only visible in the context they are needed in.
Consider a logical entity in a game and u decide that instead of a class responsibile for drawing/ticking the entities you want the code for tick/draw to be in the entity.
implement IDrawable.draw() and ITickable.tick() ensures an entity can only ever be drawn/ticked when the game expects it to. Otherwise these methods wont ever be visible.
Lesser bonus is when implementing multiple interfaces, explicit implementations let you work around cases where two interface method names collide.
Another potential scenario for explicitly implementing an interface is when dealing with an existing class that already implements the functionality, but uses a different method name. For example, if your Knife class already had a method called Slice, you could implement the interface this way:
public class Knife : ICut
{
public void Slice()
{
// slice something
}
void ICut.Cut()
{
Slice();
}
}
If the client code doesn't care about anything other than the fact that it can use the object to Cut() things, then use ICut.
Yes, but not necessarily for the given reasons.
An example:
On my current project, we are building a tool for data entry. We have certain functions that are used by all (or almost all) tabs, and we are coding a single page (the project is web-based) to contain all of the data entry controls.
This page has navigation on it, and buttons to interact with all the common actions.
By defining an interface (IDataEntry) that implements methods for each of the functions, and implementing that interface on each of the controls, we can have the aspx page fire public methods on the user controls which do the actual data entry.
By defining a strict set of interaction methods (such as your 'cut' method in the example) Interfaces allow you to take an object (be it a business object, a web control, or what have you) and work with it in a defined way.
For your example, you could call cut on any ICut object, be it a knife, a saw, a blowtorch, or mono filament wire.
For testing purposes, I think interfaces are also good. If you define tests based around the expected functionality of the interface, you can define objects as described and test them. This is a very high-level test, but it still ensures functionality. HOWEVER, this should not replace unit testing of the individual object methods...it does no good to know that 'obj.Cut' resulted in a cutting if it resulted in the wrong thing being cut, or in the wrong place.

Categories

Resources