Question:
This is a question about OOP practice. I've run into a situation while working with an API where there are a series of methods that need to be called in a specific order.
Case:
Controlling the operation of a smart sensor.
A simplified version of the interaction goes like this: first the API must be configured to interface with the sensor over TCP, the next command starts the scanning process, followed by receiving input for multiple items until the command to stop is given. At that time a similar series of disconnect commands must be given. If these are executed out of order an exception is thrown.
I see a conflict between the concepts of modularization and encapsulation here. Each of the steps is a discrete operation and thus should be encapsulated in separate methods, but they are also dependent on proper order of execution.
I'm thinking from the perspective of a later developer working on this code. It seems like someone would have to have a high level of understanding of this system before they could work on this code and that makes it feel fragile. I can add warning comments about this call order, but I'm hoping there's some principle or design pattern that might fit my situation.
Here's an example:
class RemoteTool
{
public void Config();
public void StartProcess();
public void BeginListen();
public void StopProcess();
public void StopListening();
}
class Program
{
static void Main(string[] args)
{
RemoteTool MyRemoteTool = new RemoteTool();
MyRemoteTool.Config();
MyRemoteTool.StartProcess();
MyRemoteTool.BeginListen();
// Do some stuff
MyRemoteTool.StopListening();
MyRemoteTool.StopProcess();
}
}
The closest thing I can think of is to use boolean flags and check them in in each function to assure that the prerequisite functions have already been called, but I guess I'm hoping for a better way.
Here's a method I found while looking for an answer. It's pretty simple, it helps, but doesn't solve my issue.
Essentially the class is created exactly in the question, but the dependant functions are created as protected and a public member is created to keep them in order like so:
class RemoteTool
{
public bool Running = false;
public void Run()
{
Config();
StartProcess();
BeginListen();
Running = true;
}
public void Stop() {
StopListening();
StopProcess();
Running = false;
}
protected void Config();
protected void StartProcess();
protected void BeginListen();
protected void StopProcess();
protected void StopListening();
}
The trouble is that you still have to call Stop() and Run() in the right order, but they're easier to manage and the modularization is higher.
I think the problem is related to the fact that the RemoteTool class has a contract that requires some pre-condition. e.g. : method b() has to execute() after method a().
If your language does not provide a mechanism to define these kinds of pre-conditions, you need to implement one yourself.
I agree with you that to implement this extra functionality (or these specific class contract features)
inside RemoteTool() class could degrade your current design. A simple solution could be use another class with the responsibility of enforce the needed pre-condition before call the specific method of RemoteClass.(RemoteToolProxy() can be a suitable name)
This way you will decouple the concrete functionality and the contract that says how to use it.
There are other alternatives provided by a software design approach called Design by Contract
that can give you other ways of improving your class contract.
Related
I would like to register the following items for DI using an open generic implementation and interface. I know the following example will not work, as well as other combinations I've tried with MakeGenericType, or GetGenericArguments. I would like to simply call AddRepository<MyDbContext> and then be able to inject my implementation into classes without explicitly having to register the type I am using.
Interface
public interface IRepository<TEntity>
{
}
Implementation
public class Repository<TEntity, TContext> : IRepository<TEntity>
where TEntity : class
where TContext : DbContext
{
}
Registration
public static class RepositoryServiceCollectionExtensions
{
public static IServiceCollection AddRepository<TContext>(
this IServiceCollection services) where TContext : DbContext
{
services.TryAddScoped(
typeof(IRepository<>),
typeof(Repository< , TContext>));
return services;
}
}
The dependency injection container Microsoft.Extensions.DependencyInjection and its abstraction layer does not support open generic factories. So you generally cannot achieve what you would like to do there. There’s also no support planned.
Unlike many those other dependency injection related features, this is also not really possible to patch by just providing the right wrapper or factory types. So you will actually have to change your design here.
Since you want to resolve IRepository<TEntity> and the only way to do this is by registering an equivalent open generic type, you will have to have some type Repository<TEntity> that implements your repository. That makes it impossible to retrieve the database context type from the generic type argument, so you will have to use a different way here.
You have different options to do that. For example, you could configure your Repository<TEntity> (e.g. using M.E.Options) with the context type and make that resolve the Repository<TEntity, TContext> dynamically. But since you have actual control over your database context, I would suggest either adding a marker interface or introducing another type for the context which you can then register with the container:
public class Repository<TEntity> : IRepository<TEntity>
{
public Repository(IDbContext dbContextFactory)
{ … }
}
public class MyDbContext : DbContext, IDbContext
{ … }
Then, your extension method could look like this:
public static IServiceCollection AddRepository<TContext>(this IServiceCollection services)
where TContext : DbContext, IDbContext
{
services.AddTransient(typeof(IDbContext), sp => sp.GetService<TContext>());
services.TryAddScoped(typeof(IRepository<>), typeof(Repository<>));
return services;
}
Of course, this changes how your Repository implementation works, but I don’t actually assume that you need to know the TContext type other than to inject the database context type. So this will probably still work for you.
That being said, I have too agree with Chris Pratt, that you probably don’t need this. You say that you want to introduce the repository, because “coding stores and implementations for every entity is a time consuming task” but you should really think about whether you actually need that. A generic repository is very limited in what it can do, and mostly means that you are doing just CRUD operations. But exactly that is what DbContext and DbSet<T> already do:
C: DbContext.Add, DbSet<T>.Add
R: DbContext.Find, DbSet<T>.Find
U: DbContext.Update, DbSet<T>.Update
D: DbContext.Remove, DbSet<T>.Remove
In addition, DbContext is a “unit of work” and DbSet<T> is an IQueryable<T> which gives you a lot more control and power than a generic repository could possible give you.
You cannot have a partially open generic reference. It's all or nothing. In other words, you can try:
services.TryAddScoped(
typeof(IRepository<>),
typeof(Repository<,>));
But, if that doesn't work, you'll likely need to add a type param to your AddRepository method:
public static IServiceCollection AddRepository<TEntity, TContext>(this IServiceCollection services)
where TEntity : class
where TContext : DbContext
{
services.TryAddScoped(
typeof(IRepository<TEntity>),
typeof(Repository<TEntity, TContext>));
return services;
}
Of course, I think that breaks what you're ultimately trying to achieve here: registering repositories for all the entity types in one go. You can always use a bit of reflection find all entities in your assembly (they would need to share something in common: base class, interface, etc.) and then enumerate over them and use reflection to call AddScoped on your service collection for each.
All that said, the best thing you can do here is to actually throw all this away. You don't need the repositories. EF already implements the repository and unit of work patterns. When you use an ORM like EF, you're essentially making that your data layer instead of a custom class library you create. Putting you own custom wrapper around EF not only adds entropy to your code (more to maintain, more to test, and more than can break), but it can also mess up the way EF works in many cases, leading to less efficiency in the best cases and outright introducing bugs into your application in the worst cases.
In the Head First Design Patterns book, the author often says that one should program to interface rather than implementation?
What does that mean?
Let's illustrate it with the following code:
namespace ExperimentConsoleApp
{
class Program
{
static void Main()
{
ILogger loggerA = new DatabaseLogger();
ILogger loggerB = new FileLogger();
loggerA.Log("My message");
loggerB.Log("My message");
}
}
public interface ILogger
{
void Log(string message);
}
public class DatabaseLogger : ILogger
{
public void Log(string message)
{
// Log to database
}
}
public class FileLogger : ILogger
{
public void Log(string message)
{
// Log to File
}
}
}
Suppose you are the Logger developer and the application developer needs a Logger from you. You give the Application developer your ILogger interface and you say to him he can use but he doesn't have to worry about the implementation details.
After that you start developing a FileLogger and Databaselogger and you make sure they follow the interface that you gave to the Application developer.
The Application developer is now developing against an interface, not an implementation. He doesn't know or care how the class is implemented. He only knows the interface. This promotes less coupling in code and it gives you the ability to (trough configuration files for example) easily switch to another implementation.
Worry more about what a class does rather than how it does it. The latter should be an implementation detail, encapsulated away from clients of your class.
If you start with an interface, you're free to inject in a new implementation later without affecting clients. They only use references of the interface type.
It means that when working with a class, you should only program against the public interface and not make assumptions about how it was implemented, as it may change.
Normally this translates to using interfaces/abstract classes as variable types instead of concrete ones, allowing one to swap implementations if needed.
In the .NET world one example is the use of the IEnumerable/IEnumerator interfaces - these allow you to iterate over a collection without worrying how the collection was implemented.
It is all about coupling. Low coupling is a very important property* of software architecture. The less you need to know about your dependency the better.
Coupling can be measured by the number of assumptions you have to make in order to interact/use your dependency (paraphrasing M Fowler here).
So when using more generic types we are more loosely coupled. We are for example de-coupled from a particular implementation strategy of a collection: linked list, double linked list, arrays, trees, etc. Or from the classic OO school: "what exact shape it is: rectangle, circle, triangle", when we just want to dependent on a shape (in old school OO we apply polymorphism here)
Code examples are C# but this is a general OO question.
I know according to OO rules, class coupling should be minimised and members should be kept private wherever possible, etc.
Consider this example:
You are writing an esoteric program which has some sort of data set (I'm not talking about System.Data.DataSet) which is used in literally every facet of the program. In fact, the program basically exists just to load, display, manipulate, and save the data set. Furthermore, there can only ever be one data set loaded at any time, and it is loaded when the program opens.
If we follow OO rules strictly, we would have
public void ShowSomeGraphs(IData data)
{
// do stuff with data which implements IData
}
however we could potentially store a public static Data member in Program, for example.
public void ShowSomeGraphs()
{
// do stuff with Program.Data
}
On one hand, we have traded a slightly shorter function signature for vastly increased class coupling. On the other hand, we are no longer passing a Data parameter to practically every function, everywhere.
The right answer probably is: Avoid class coupling wherever possible. The local Data variables are just pointers so the memory overhead is negligible, and because the classes are decoupled they can be used elsewhere at a later date.
Though realistically speaking, the structure of the Data class will likely be phenomenally different in a different application, so it's not like you can just pull a class from this program and drop it in somewhere else without any tweaks. The extra time and effort required to write the classes in such a way that they can just be dropped in might be difficult to justify to a stakeholder.
I'm working on this sort of program now, and I have used the OO-canon approach: Data parameters are passed around where needed I have minimised class coupling with an IData interface to generalise the data set for future code re-use. Given the application, I'm almost certain this code won't ever be re-used. Without these extra interfaces and abstraction, the program would have worked exactly the same as far as the end user is concerned, but would have represented significantly less headaches and development time for me.
What do you think about this? Do you think it's justifiable to spend all the extra time to write the interfaces and generalisations to ensure classes are decoupled where possible, especially when you can't see the classes being use elsewhere later?
Don't agonise over it. Seriously.
Software paradigms/patterns are there to help us and not to be followed dogmatically.
You make it clear in your question that you consider the loose coupling overkill, and you can justify why. Therefore, don't use it.
How about using the singleton pattern to provide a method or read-only property to get the IData interface? This way you're only coupled to a very thin singleton class and all your interactions with the data set are done through the IData interface.
(I would definitely avoid the tight coupling. Even if you don't plan to do much with this app chances are that you will run into an issue during development which will force you to touch significantly more code than if you accessed the data via an interface.)
Code sample of the singleton solution proposed above:
using System;
public class MyClass {
public static void Main() {
// simple usage:
Console.WriteLine("From Main: " + Singleton.Instance.IMyData.GetData());
// client code from another type:
new ClientObj().DoWork();
Console.ReadKey();
}
}
public sealed class Singleton {
// standard singleton stuff:
private static readonly Singleton _instance = new Singleton();
private Singleton(){}
public static Singleton Instance {get { return _instance; }}
// data interface stuff:
private MyData _myData = new MyData();
public IData IMyData {get { return _myData; }}
}
// the interface:
public interface IData {
string GetData();
}
// concrete implementation of the data class
public class MyData : IData {
public string GetData() {return "Hello World!";}
}
// example of a type using the singleton and the IData interface
public class ClientObj {
public void DoWork() {
IData data = Singleton.Instance.IMyData;
string str = data.GetData();
Console.WriteLine("From other obj: " + str);
}
}
Some caveats: The code sample above is completely stripped down to show the concept of a singleton and shared interface. There is no thread safety implemented, there is no initialization of the data object etc.
Well, there's one big assumption in your text: There will always only be one data set in the program. Are you sure that condition will hold for all time? There was a time where word processors could only hold one text at a time. Today it's standard to be able to have several files open at once. I'd also not be surprised if the first web browsers could only open one web page at a time. Today nobody would use a web browser which could not have several pages open at the same time. I think the sort of object where you can say there will be for certain only one of it in the program, ever, is quite rare. Indeed, the only thing which I would make a global object or singleton would be object factories.
On the other hand, passing the object around for each function call seems to be overkill to me, too. Therefore I would go for the middle ground: Have the objects remember that "global" object, so you only have to pass it via the constructor. This limits each single object to one Data object, but still allows you to easily have several Data objects in your program should you ever decide to.
Context: .NET, C#, but the question is about OOP in general.
When I write a class that should act as a "service", like a socket listener, or a timer, I see two approaches when it comes to coding it:
Create a constructor, and inside the constructor, immediately start the background task. For instance:
public class MyTimer
{
private readonly TimeSpan interval;
public MyTimer(TimeSpan interval)
{
this.interval = interval;
StartTicking();
}
private void StartTicking()
{
// do the ticking logic
}
}
Create a constructor that accepts the class' settings, and add an explicit method for starting up:
public class MyTimer
{
private readonly TimeSpan interval;
public MyTimer(TimeSpan interval)
{
this.interval = interval;
}
public void StartTicking()
{
// do the ticking logic
}
}
I tend to think that the second approach is better:
A. The constructor is used only for creating a valid instance, keeping it minimal and clean.
B. The developer who actually uses my class is less astonished.
C. The hardware resources are not overused, since the "service" class does not immediately use them.
What do you think? Is it only a matter of coding style, or is it more than that?
Keep your constructor minimal, and require the calling code to call a specific function in order to do anything but the most simple initialization. This is what the Stopwatch class does in .NET, for instance.
Besides avoiding surprises for the person invoking the constructor, this also allows you to make better use of Dependency Injection (i.e. having your class injected into the constructor of a class that needs it, but which doesn't want to use it right way).
I've also found that certain types of bugs are more difficult to catch when they occur in constructors than when they are in some other method.
Don't start running in your constructor.
Users of your API won't expect that, and it makes your class harder to use
From an exception handling standpoint, you want to be able to report an error that happens when constructing an object, separately from an error that happens during execution.
It prevents sharing instances of your object, if you ever wanted to do something like a static factory singleton pattern.
I would second StriplingWarrior's point that there are many good reasons, like dependency injection, where object creation needs to happen first so that some other class can run it later.
Nearly every service-type class that I've seen exposes methods to start and stop it. If it is auto-starting, it is usually very explicitly so (the class name might be MyAutostartingTimer or something..)
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.