Interface reference variables - oop

I am going over some OO basics and trying to understand why is there a use of Interface reference variables.
When I create an interface:
public interface IWorker
{
int HoneySum { get; }
void getHoney();
}
and have a class implement it:
public class Worker : Bee, IWorker
{
int honeySum = 15;
public int HoneySum { get { return honeySum; } }
public void getHoney()
{
Console.WriteLine("Worker Bee: I have this much honey: {0}", HoneySum);
}
}
why do people use:
IWorker worker = new Worker();
worker.getHoney();
instead of just using:
Worker worker3 = new Worker();
worker3.getHoney();
whats the point of a interface reference variable when you can just instatiate the class and use it's methods and fields that way?

If your code knows what class will be used, you are right, there is no point in having an interface type variable. Just like in your example. That code knows that the class that will be instantiated is Worker, because that code won't magically change and instantiate anything else than Worker. In that sense, your code is coupled with the definition and use of Worker.
But you might want to write some code that works without knowing the class type. Take for example the following method:
public void stopWorker(IWorker worker) {
worker.stop(); // Assuming IWorker has a stop() method
}
That method doesn't care about the specific class. It would handle anything that implements IWorker.
That is code you don't have to change if you want later to use a different IWorker implementation.
It's all about low coupling between your pieces of code. It's all about maintainability.

Basically it's considered good programming practice to use the interface as the type. This allows different implementations of the interface to be used without effecting the code. I.e. if the object being assigned was passed in then you can pass in anything that implements the interface without effecting the class. However if you use the concrete class then you can only passin objects of that type.
There is a programming principle I cannot remember the name of at this time that applies to this.

You want to keep it as generic as possible without tying to specific implementation.

Interfaces are used to achieve loose coupling between system components. You're not restricting your system to the specific concrete IWorker instance. Instead, you're allowing the consumer to specify which concrete implementation of IWorker they'd like to use. What you get out of it is loosely dependent components and better flexibility.

One major reason is to provide compatibility with existing code. If you have existing code that knows how to manipulate objects via some particular interface, you can instantly make your new code compatible with that existing code by implementing that interface.
This kind of capability becomes particularly important for long-term maintenance. You already have an existing framework, and you typically want to minimize changes to other code to fit your new code into the framework. At least in the ideal case, you do this by writing your new code to implement some number of existing interfaces. As soon as you do, the existing code that knows how to manipulate objects via those interfaces can automatically work with your new class just as well as it could with the ones for which it was originally designed.

Think about interfaces as protocols and not classes i.e. does this object implement this protocol as distinct from being a protocol? For example can my number object be serialisable? Its class is a number but it might implement an interface that describes generally how it can be serialised.
A given class of object may actually implement many interfaces.

Related

Network storage design pattern

Let's say I have a few controllers. Each controller can at some point create new objects which will need to be stored on the server. For example I can have a RecipeCreationViewController which manages a form. When this form is submitted, a new Recipe object is created and needs to be saved on the server.
What's the best way to design the classes to minimize complexity and coupling while keeping the code as clean and readable as possible?
Singleton
Normally I would create a singleton NetworkAdapter that each controller can access directly in order to save objects.
Example:
[[[NetworkAdapter] sharedAdapter] saveObject:myRecipe];
But I've realized that having classes call singletons on their own makes for coupled code which is hard to debug since the access to the singleton is hidden in the implementation and not obvious from the interface.
Direct Reference
The alternative is to have each controller hold a reference to the NetworkAdapter and have this be passed in by the class that creates the controller.
For example:
[self.networkAdapter saveObject:myRecipe];
Delegation
The other approach that came to mind is delegation. The NetworkAdapter can implement a "RemoteStorageDelegate" protocol and each controller can have a remoteStorageDelegate which it can call methods like saveObject: on. The advantage being that the controllers don't know about the details of a NetworkAdapter, only that the object that implements the protocol knows how to save objects.
For example:
[self.remoteStorageDelegate saveObject:myRecipe];
Direct in Model
Yet another approach would be to have the model handle saving to the network directly. I'm not sure if this is a good idea though.
For example:
[myRecipe save];
What do you think of these? Are there any other patterns that make more sense for this?
I would also stick with Dependency Injection in your case. If you want to read about that you will easily find good articles in the web, e.g. on Wikipedia. There are also links to DI frameworks in Objective C.
Basically, you can use DI if you have two or more components, which must interact but shouldn't know each other directly in code. I'll elaborate your example a bit, but in C#/Java style because I don't know Objective C syntax. Let's say you have
class NetworkAdapter implements NetworkAdapterInterface {
void save(object o) { ... }
}
with the interface
interface NetworkAdapterInterface {
void save(object o);
}
Now you want to call that adapter in a controller like
class Controller {
NetworkAdapterInterface networkAdapter;
Controller() {
}
void setAdapter(NetworkAdapterInterface adapter) {
this.networkAdapter = adapter;
}
void work() {
this.networkAdapter.save(new object());
}
}
Calling the Setter is where now the magic of DI can happen (called Setter Injection; there is also e.g. Constructor Injection). That means that you haven't a single code line where you call the Setter yourself, but let it do the DI framework. Very loose coupled!
Now how does it work? Typically with a common DI framework you can define the actual mappings between components in a central code place or in a XML file. Image you have
<DI>
<component="NetworkAdapterInterface" class="NetworkAdapter" lifecycle="singleton" />
</DI>
This could tell the DI framework to automatically inject a NetworkAdapter in every Setter for NetworkAdapterInterface it finds in your code. In order to do this, it will create the proper object for you first. If it builds a new object for every injection, or only one object for all injections (Singleton), or e.g. one object per Unit of Work (if you use such a pattern), can be configured for each type.
As a sidenote: If you are unit testing your code, you can also use the DI framework to define completely other bindings, suitable for your test szenario. Easy way to inject some mocks!

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

Is it bad practice for a class to have only static fields and methods?

I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.
Is it bad practice for a class to contain only static member variables and static methods?
No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.
EDIT: As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.
As long as the class has no internal state and is essentially what is known as a leaf class (utility classes fall into this category), in other words it is independent of other classes. It is fine.
The Math class being a prime example.
Sounds reasonable.
Note: Classes that do this often have a private no-arg constructor just so that the compiler yields an error if a programmer tries to create an instance of the static class.
Static methods don't worry me much (except for testing).
In general, static members are a concern. For example, what if your app is clustered? What about start-up time -- what kind of initialization is taking place? For a consideration of these issues and more, check out this article by Gilad Bracha.
It's perfectly reasonable. In fact, in C# you can define a class with the static keyword specifically for this purpose.
Just don't get carried away with it. Notice that the java.lang.Math class is only about math functions. You might also have a StringUtilities class which contains common string-handling functions which aren't in the standard API, for example. But if your class is named Utilities, for example, that's a hint that you might want to split it up.
Note also that Java specifically introduced the static import: (http://en.wikipedia.org/wiki/Static_import)
Static import is a feature introduced
in the Java programming language that
members (fields and methods) defined
in a class as public static to be used
in Java code without specifying the
class in which the field is defined.
This feature was introduced into the
language in version 5.0.
The feature provides a typesafe
mechanism to include constants into
code without having to reference the
class that originally defined the
field. It also helps to deprecate the
practice of creating a constant
interface: an interface that only
defines constants then writing a class
implementing that interface, which is
considered an inappropriate use of
interfaces[1].
The mechanism can be used to reference
individual members of a class:
import static java.lang.Math.PI;
import static java.lang.Math.pow;
or all the static members of a class:
import static java.lang.Math.*;
While I agree with the sentiment that it sounds like a reasonable solution (as others have already stated), one thing you may want to consider is, from a design standpoint, why do you have a class just for "utility" purposes. Are those functionals truly general across the entire system, or are they really related to some specific class of objects within your architecture.
As long as you have thought about that, I see no problem with your solution.
The Collections class in Java SDK has static members only.
So, there you go, as long as you have proper justification -- its not a bad design
Utility methods are often placed in classes with only static methods (like StringUtils.) Global constants are also placed in their own class so that they can be imported by the rest of the code (public final static attributes.)
Both uses are quite common and have private default constructors to prevent them from being instantiated. Declaring the class final prevents the mistake of trying to override static methods.
If by static member variables you did not mean global constants, you might want to place the methods accessing those variables in a class of their own. In that case, could you eleborate on what those variables do in your code?
This is typically how utility classes are designed and there is nothing wrong about it. Famous examples include o.a.c.l.StringUtils, o.a.c.d.DbUtils, o.s.w.b.ServletRequestUtils, etc.
According to a rigid interpretation of Object Oriented Design, a utility class is something to be avoided.
The problem is that if you follow a rigid interpretation then you would need to force your class into some sort object in order to accomplish many things.
Even the Java designers make utility classes (java.lang.Math comes to mind)
Your options are:
double distance = Math.sqrt(x*x + y*y); //using static utility class
vs:
RootCalculator mySquareRooter = new SquareRootCalculator();
mySquareRooter.setValueToRoot(x*x + y*y);
double distance;
try{
distance = mySquareRooter.getRoot();
}
catch InvalidParameterException ......yadda yadda yadda.
Even if we were to avoid the verbose method, we could still end up with:
Mathemetician myMathD00d = new Mathemetician()
double distance = myMathD00d.sqrt(...);
in this instance, .sqrt() is still static, so what would the point be in creating the object in the first place?
The answer is, create utility classes when your other option would be to create some sort of artificial "Worker" class that has no or little use for instance variables.
This link http://java.dzone.com/articles/why-static-bad-and-how-avoid seems to go against most of the answers here. Even if it contains no member variables (i.e. no state), a static class can still be a bad idea because it cannot be mocked or extended (subclassed), so it is defeating some of the principles of OO
I wouldn't be concerned over a utility class containing static methods.
However, static members are essentially global data and should be avoided. They may be acceptable if they are used for caching results of the static methods and such, but if they are used as "real" data that may lead to all kinds of problems, such as hidden dependencies and difficulties to set up tests.
From TSLint’s docs:
Users who come from a Java-style OO language may wrap their utility functions in an extra class, instead of putting them at the top level.
The best way is to use a constant, like this:
export const Util = {
print (data: string): void {
console.log(data)
}
}
Examples of incorrect code for this rule:
class EmptyClass {}
class ConstructorOnly {
constructor() {
foo();
}
}
// Use an object instead:
class StaticOnly {
static version = 42;
static hello() {
console.log('Hello, world!');
}
}
Examples of correct code for this rule:
class EmptyClass extends SuperClass {}
class ParameterProperties {
constructor(public name: string) {}
}
const StaticOnly = {
version: 42,
hello() {
console.log('Hello, world!');
},
};

Rule of thumb for naming wrapper classes

I find myself creating a significant number of wrapper classes, purely because I want to mock out the behaviour of
Classes that don't lend themselves well to the RhinoMocks isolation model (for instance like DirectoryInfo or WindowsIdentity)
Native Win API methods (I normally collect all the methods I need into a single class and wrap the native calls as a class method)
I then find myself appending the class that is wrapped with a 'W' (to indicate that it's a wrapper) and so I end up with DirectoryInfoW (as opposed to DirectoryInfoWrapper which seems rather verbose). Similarly, I end up with wrapped native methods called NativeMethods.DuplicateTokenW.
What would be a good rule of thumb to follow when naming wrapper classes?
Naming conventions are whatever works for the team that you're working with. As long as everyone's ok with a particular convention, then it's ok.
I tend to prefer the more verbose version though, i.e. DirectoryInfoWrapper, rather than having a single letter that doesn't explain anything to anyone who's not familiar with the code. But that's just me.
I'll agree with aberrant80 , if everyone agrees with the convention you are using, then it'll work.
I personally prefer using names that are shorter and descriptive to the class's purpose. At least at the interface level. If you're using a mock framework, then IDirectory or IDirectoryInfo would be a decent set of names, while DirectoryInfoW or DirectoryInfoWrapper would be an interface implementer.
A better example might be wrapping an HttpRequest; define an IRequest to state 'this is what is important to my application', then Request, HttpRequestWrapper, Request, etc would be implementers.
So, to summarize, try and use descriptive, non-overly-verbose interface names.
Just as a side note, I found a more aesthetically pleasing (well, to me) way of wrapping native method calls:
public class NativeMethods
{
// made virtual so that it can be mocked - I don't really want
// an interface for this class!
public virtual bool RevertToSelf()
{
return WinApi.RevertToSelf();
}
...
private static class WinApi
{
[DllImport("advapi32.dll")]
public static extern bool RevertToSelf();
...
}
}
i.e. avoid name collision by encapsulating native method calls in a private nested class.
No 'good' solution to the wrapper class naming issue though, I'd probably go with aberrant80's suggestion and explicitly call my wrappers wrappers.
If you are using C++, you can use namespaces and then just re-use the same class name. For example:
namespace WrapperNamespace
{
class MyClass {...};
}
namespace InternalNamespace
{
class MyClass {...};
}

Is the function of interfaces primarily for using functions without knowing how a class is built?

As I understand interfaces they are contracts, I interpret it as the contract word, ie must have what is specified in the interface (ex open, close, read, write for an interface handling files).
But what im having a hard time grasping is why you would need to have an interface that tells you what the class must be able to do at all, wouldnt you know that already since you wrote it in the interface specification?
The only reason I can see for interfaces is in large projects where you want to be able to use a class without really knowing how it is built. By seeing what the interface requires will allow you to know how to use it.
Which leads me to wonder why I should use (or if I should) interfaces in projects that I will be the only one working on. Im pretty sure there are more uses for it that im not seeing.
I took most of my assumptions and interpretations from this question and this vbforums post
You're right in that interfaces specify the contract but the implementaiton can be vastly different.
Simple example: lists in Java. List is an interface. Two common implementations are ArrayList and LinkedList. Each behaves different but honours the same contract. By that I mean that ArrayList has O(1) (constant) access whereas LinkedList has O(n) access.
If you don't yet understand what O(1) and O(n) mean, I suggest you take a look at the Plain english explanation of Big O.
The reason you do this even on your own code (ie something that isn't or won't be a public API) is to:
facilitate unit testing: you can mock up an interface whereas you can't (or can't easily) mock up a class; and
to allow you to change the implementation later without affecting the calling code.
Interfaces are useful when you have two classes which need to work together but should be decoupled from each other as much as possible. A common example of this is when you use listeners to connect model and view together in the model-view-controller design pattern.
For example, let's say you had a GUI application where users could log in and log out. When users log out you might, say, change your "Currently logged in as So-and-So" label and close all of the visible dialog windows.
Now you have a User class with a logOut method, and whenever logOut is called you want all of these things to happen. One way to do that is have the logOut method handle all of these tasks:
// Bad!
public void logOut() {
userNameLabel.setText("Nobody is logged in");
userProfileWindow.close();
}
This is frowned upon because your User class is now tightly coupled to your GUI. It would be better to have the User class be dumber and not do so much. Instead of closing userProfileWindow itself it should just tell userProfileWindow that the user has logged out and let userProfileWindow do whatever it wants to do (it wants to close itself).
The way to do this is by creating a generic UserListener interface with a method loggedOut that is called by the User class when the user logs out. Anybody who wants to know when the user logs in and logs out will then implement this interface.
public class User {
// We'll keep a list of people who want to be notified about logouts. We don't know
// who they are, and we don't care. Anybody who wants to be notified will be
// notified.
private static List<UserListener> listeners;
public void addListener(UserListener listener) {
listeners.add(listener);
}
// This will get called by... actually, the User class doesn't know who's calling
// this or why. It might be a MainMenu object because the user selected the Log Out
// option, or an InactivityTimer object that hasn't seen the mouse move in 15
// minutes, who knows?
public void logOut() {
// Do whatever internal bookkeeping needs to be done.
currentUser = null;
// Now that the user is logged out, let everyone know!
for (UserListener listener: listeners) {
listener.loggedOut(this);
}
}
}
// Anybody who cares about logouts will implement this interface and call
// User.addListener.
public interface UserListener {
// This is an abstract method. Each different type of listener will implement this
// method and do whatever it is they need to do when the user logs out.
void loggedOut(User user);
}
// Imagine this is a window that shows the user's name, password, e-mail address, etc.
// When the user logs out this window needs to take action, namely by closing itself so
// this information isn't viewable by other users. To get notified it implements the
// UserListener interface and registers itself with the User class. Now the User.logOut
// method will cause this window to close, even though the User.java source file has no
// mention whatsoever of UserProfileWindow.
public class UserProfileWindow implements UserListener {
public UserProfileWindow() {
// This is a good place to register ourselves as interested observers of logout
// events.
User.addListener(this);
}
// Here we provide our own implementation of the abstract loggedOut method.
public void loggedOut(User user) {
this.close();
}
}
The order of operations will look like this:
The application starts and a user logs in. She opens her UserProfileWindow.
The UserProfileWindow adds itself as a UserListener.
The user goes idle and doesn't touch the keyboard or mouse for 15 minutes.
An imagined InactivityTimer class notices and calls User.logOut.
User.logOut updates the model, clearing the currentUser variable. Now if anybody asks, there's nobody logged in.
User.logOut loops through its listener list, calling loggedOut() on each listener.
The UserProfileWindow's loggedOut() method is invoked, which closes the window.
This is great because this User class knows absolutely nothing about who needs to know about log out events. It doesn't know that the user name label needs to be updated, that the profile window needs to be closed, none of that. If later we decide more things need to be done when a user logs out, the User class does not need to be changed at all.
So, the listener pattern is one example of where interfaces are super useful. Interfaces are all about decoupling classes, removing ties and dependencies between classes that need to interact with each other but should not have strong ties in their code to each other.
But what im having a hard time grasping is why you would need to have an interface that tells you what the class must be able to do at all, wouldnt you know that already since you wrote it in the interface specification?
It is also good when you are writing externally available code. In this case the code writer is not the user of the Interface. If you are delivering a library to users, you may want to document only the Interface, and allow the Class to change based on context or to evolve over time without changing the Interface.
Suppose you're writing a set of classes that implements guns. You might have a Pistol, a Rifle, and a MachineGun. Then, suppose you decide to use these classes in such a way that you'd like to perform the fire() action on each of these guns. You could do it this way:
private Pistol p01;
private Pistol p02;
private Rifle r01;
private MachineGun mg01;
public void fireAll() {
p01.fire();
p02.fire();
r01.fire();
mg01.fire();
}
That kind of sucks, because you have to change code in a few places if you add or remove guns. Or even worse, suppose you want to be able to add and remove guns at runtime: it becomes even harder.
Let's make an interface that each of the above guns will implement, call it Firearm. Now we can do this.
private Firearm[] firearms;
public void fireAll() {
for (int i = 0; i < firearms.length; ++i) {
firearms[i].fire();
}
}
That lends itself to changes a little bit better, wouldn't you say?
Let's say you have two classes Car and Gorilla. These two classes have nothing to do with each other. But, let's say you also have a class that can crush things. Instead of defining a method that takes a Car and crushes it and then having a separate method that takes a Gorilla and crushes it, you make an Interface called ICrushable ...
interface ICrushable
{
void MakeCrushingSound();
}
Now you can have your car and your Gorilla implement ICrushable and your Car implement ICrushable and your crusher can then operate on an ICrushable instead of a Car and a Gorilla ...
public class Crusher
{
public void Crush(ICrushable target)
{
target.MakeCrushingSound();
}
}
public class Car : ICrushable
{
public void MakeCrushingSound()
{
Console.WriteLine("Crunch!");
}
}
public class Gorilla : ICrushable
{
public void MakeCrushingSound()
{
Console.WriteLine("Squish!!");
}
}
static void Main(string[] args)
{
ICrushable c = new Car(); // get the ICrushable-ness of a Car
ICrushable g = new Gorilla(); // get the ICrushable-ness of a Gorilla
Crusher.Crush(c);
Crusher.Crush(g);
}
And Viola! You have a Crusher that can crush Cars and get "Crunch!" and can crush Gorillas and get "Squish!". Without having to go through the process of finding a type-relationship between Cars and Gorillas and with compile-time type checking (instead of a runtime switch statement).
Now, consider something less silly ... an Class that can be compared (IComparable) for example. The class will define how you compare two things of it's type.
Per comment: Okay, let's make it so we can sort an array of Gorillas. First, we add something to sort by, say Weight (please ignore the dubious business logic of sorting Gorillas by weight ... it's not relevant here). Then we implement ICompararble ...
public class Gorilla : ICrushable, IComparable
{
public int Weight
{
get;
set;
}
public void MakeCrushingSound()
{
Console.WriteLine("Squish!!");
}
public int CompareTo(object obj)
{
if (!(obj is Gorilla))
{
throw (new ArgumentException());
}
var lhs = this;
var rhs = obj as Gorilla;
return (lhs.Weight.CompareTo(rhs.Weight));
}
}
Notice we have "gotten around" the restriction of single inheritance that many languages have. We are allowed to implement as many interfaces as we like. Now, just by doing that, we can use functionality that was written more than 10 years ago on a class I just wrote today (Array.Sort, Array.BinarySearch). We can now write the following code ...
var gorillas = new Gorilla[] { new Gorilla() { Weight = 900 },
new Gorilla() { Weight = 800 },
new Gorilla() { Weight = 850 }
};
Array.Sort(gorillas);
var res = Array.BinarySearch(gorillas,
new Gorilla() { Weight = 850 });
My Gorillas get sorted and binary search finds the matching Gorilla with the Weight of 850.
If you ever want to revisit your old code, you will thank yourself for having built yourself some interfaces. Nothing is more frustrating than wanting to implementing a new type of something that exists, only to realize you do not remember what a new object had to have.
In Java, you can implement multiple interfaces, which sort of simulates multiple inheritance (an object with multiple parent objects). You can only extend one superclass.
No one forces you to write interface and there is no language enforces that even. Its a best practice and idiom that a good programmer would follow. You are the only one to use your code, and ya, you can write what you like but what if you leave the project and someone else has to maintain and/or extend it? Or what if some other projects consider using your code? Or even what if after a while, you have to revisit your code for adding features or refactoring? You would create a nightmare for these sorts of things. It will be hard to understand what your object relationships and contracts established b/w them.
Abstraction:
Code written to use an interface is reusable an never needs to change. In the below case, the sub will work with System.Array, System.ArrayList, System.Collection.CollectionBase, List of T, because they all implement IList. An existing class can easily implement an interface even when the class inherits another class.
You could even write your class to implement IList to us in the sub. Or another program could also implement the interface to use in the sub.
public sub DoSomething(byval value as IList)
end sub
You can also use multiple interfaces in a class, so a class can be both a IList and IEnumerable, in most languages you can on inherit one class.
I would also look at how they are used in the various frameworks.
As I understand your question why do we need Interfaces ? right ?
Well we don't need them :)
In C++ for example, when you define a template... say a dummy function that looks like ::
template <typename T>
void fun(const T& anObjectOfAnyType)
{
anyThing.anyFunction();
}
you can use this function anywhere with any type that has a function called anyFunction...
the only thing that the compiler is going to do, is to replace T with the name of the type,
and compile the new piece of code...
This is very error prone in fact. The reason is that if we plug in a type which does not have a anyFunction then we are going to get an error, that error is different every time,
every line that can not be translated by the compiler will issue an error for it. You get A LOT of errors for the ONLY MISSING THING!
The new type does not have the required functions to work correctly with our fun for example.
Now interfaces solve this whole issue, how ?
If the type has the required functions, then it is suitable, if not then the compiler will issue an error that the type is not suitable.
The template example is just for clarification, and if you want to imaging what will happen if java is without interfaces, then the only thing you have to do is to check for the existence of every function manually in every class, where you assume that class implements a particular function. The dirty work is done by the compiler :)
Thanks,
an interface reduces what the client is dependent on (http://en.wikipedia.org/wiki/Dependency_inversion_principle). it allows for multiple implementations and the ability to change implementations at run time.