Public static data used throughout program - oop

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.

Related

Does Inversion of Control lead to Side Effects?

A question I've been struggling a lot with lately is how, in my opinion, Inversion of Control
breaks Encapsulation and can easily lead to side effects in a program. However, at the same time, some of the
big advatages of IoC is loose coupling/modularity as well as Test Driven Design making Unit testing a class much easier (I think TDD is really pushing IoC in the industry).
Here is my argument againt IoC.
If the injected types are Immutable and Pure then IoC is acceptable, for example primitive types. However, if they are impure
and can modify the state of the program or hold their own state then side effects can easily
occur.
Take the following example C#/Pseudo:
public class FileSearcher: IFileSearcher
{
private readonly string searchPath;
public void SetSearchPath(string path)
{
searchPath = path;
}
public List<string> FindFiles(string searchPattern)
{
//...Search for files with searchPattern starting at searchPath
}
}
public class PlayListViewer
{
public PlayListViewer(string playlistName, IFileSearcher searcher)
{
searcher.SetSearchPath($"playlists/{playlistName}")
}
public List<string> FindSongNames()
{
return searcher.FindFiles(
"*.mp3|*.wav|*.flac").Select(f => Path.GetFileName(f))
}
//....other methods
}
public class Program
{
public static void Main()
{
var searcher = FileSearcher();
var viewer = PlayListViewer("Hits 2021", searcher);
searcher.SetSearchPath("C:/Users") //Messes up search path
var pictures = searcher.FindFiles("*.jpg") //Using searcher for something else
viewer
.FindSongNames()
.ForEach(s => Console.WriteLine(s)) //WRONG SONGS
}
}
In the (very uncreative) example above, The PlaylistViewer has a method for finding songs within a playlist. It
attempts to set the correct search path for the playlist on the injected IFileSearcher, but the User of the class
overwrote the path. Now when they try to find the songs in the playlist, the results are incorrect.
The Users of a class do not always know the implementation of the class they're using and don't know the side
effects they're causing by mutating the objects they passed in.
Some other simple examples of this:
The Date Class in Java is not immutable and has a setDate (deprecated now) method. The following could occur:
date = new Date(2021, 10, 1)
a = new A(date)
a.SomethingInteresting() //Adds 1 year to the Date using setDate
b = new B(date) //No longer the correct date
I/O abstractions such as streams:
audioInput = new MemoryStream()
gainStage = new DSPGain(audioInput)
audioInput.write(....)
audioInput.close()
gainStage.run() //Error because memory stream is already closed
etc...
Other issues can come up too if the Object gets passed to multiple classes that use it across different threads concurrently. In these cases
a User might not know/realize that class X internally is launching/processing on a different thread.
I think the simple, and functional, answer would be to only write pure functions and immutable classes but that isn't always practical in the real world.
So when should IoC really be used? Maybe only when the injected types are immutable and pure and anything else should be composed and encapsulated? If that's the answer, then what does that mean for TDD?
First, Inversion of Control is not the same as Dependency Injection. DI is just one implementation of IoC. This question makes more sense if we limit it to just DI.
Second, Dependency Injection is orthogonal to Test Driven Development. DI can make writing unit tests easier, which may encourage you to write more unit tests; but that does not necessitate TDD. You can certainly use DI without TDD, and I suspect that's the way the vast majority of developers use it. TDD is not a widespread practice.
Conversely, practicing TDD may encourage you to implement DI; but that is far from a requirement. Don't confuse statements like, "TDD and DI work well together," with "TDD and DI require each other." They can be used together or separately.
Finally, if you want to use your DI container as a repository of global variables, you certainly can. This approach of storing mutable state and injecting it across your application brings the same caveats and pitfalls as sharing mutable state anywhere else.
That should be the main takeaway from this question: not the downside of DI or TDD, but the downside of mutable state in general. You don't need DI to run afoul of mutable state. Trouble with mutable state is virtually guaranteed in the practice of imperative programming, which is by far the most common programming paradigm.
Consider that the functional programmers might really be onto something with their declarative approach.

What are the practical difference between declaring a function private vs public?

So as I've been reading/learning about classes and the methods within them I've found very little about the practical differences between declaring a method as public versus private.
I know that the difference is a private class can only be accessed within the class, while a public method can be accessed from code outside the class (other classes, functions). But what I really want to know is:
Why would you want/not want to declare it one way or another when deploying an application?
Are there best practices that can guide whether to declare a method public vs private?
Also, I don't know if it matters, but I am learning primarily VB.Net and C# in a web application environment, so specifics to that would help.
Encapsulation means that you should think of each class as a machine that provides a service. For example, a chair allows you to sit on it, or a lawnmower allows you to cut your lawn.
The private methods pertain to the machine's internal workings. In contrast, the public methods relate to how you (other classes) interact with the machine.
Example one: Chair...
When sitting on a chair, you don't need to know volume of stuffing or the number of staples, you basically need to know whether or not it's occupied and if it's stable.
Public methods: IsStable, IsOccupied, Sit
Private methods: CalculateStuffingVolume, CountNumberOfStaples
Example two: Lawnmower...
For the lawnmower, you need to know if it has enough fuel (or is plugged in), if the blades are sharp, and be able to turn it on.
Public methods: GetFuelLevel, IsBladesSharp, TurnOn, TurnOff
Private methods: Combust, etc, Too many to imagine.
Conclusion:
So when you're developing all you will see is...
Example one: Chair.Sit, Chair.IsStable and Chair.IsOccupied
or
Example two: Lawnmower.GetFuelLevel, Lawnmower.IsBladesSharp, Lawnmower.TurnOn, LawnMower.TurnOff
As a developer, you will not have to think about number of threads in the uphosltry, the colour of the fuel cap, the number of RPM of the blades or whether the chair is glued or stapled together. This distinction makes it much easier to put your application together without being swamped in detail. Additionally, it allows programmers to expose only necessary information which adds a level of security. As John mentioned, this prevents the Person class from calling Lawnmower.Combust(fuel) when they're not supposed to.
If the method is private, then you don't have to think about outside classes calling it incorrectly.
One of the benefits of this is that it allows for a separation between the interface to your class (the public parts of it), and the implementation of it. If nobody knows how you implemented your class (that is, if there is no code that depends on how you implemented it), then you're free to change the way you implemented it without breaking any other code.
It's one of the most importand principles of the object-oriented programming -- encapsulation.
A class usually provides a (public) interface. E.g. (pseudocode):
class Rectangle {
private length;
private width;
public getPerimeter() {
// return calculatePerimeterOld();
return calculatePerimeterNew();
}
private calculatePerimeterOld() {
// old variant
}
private calculatePerimeterNew() {
// Here the perimeter is caltulated.
// so: perimeter = 2 * (length + width)
// or so: perimeter = 2 * (length) + 2 * (width)
// or maybe so: perimeter = length + width + length + width - (0.5 * length) + 2 * 0.25 * length)
return perimeter;
}
}
I can change my private methods however I want. I can rename or replace them with oher methods. But my public interface will stay the same -- and it has to stay the same, because it's a contract I sign, when I'm defining a mehod as public. Everything, what is signed as private is my "blackbox" and I can do there whatever I want.
It's the main reason. Another reason is, that we should not provide the user(-s) of our class with methods/informations, they don't need. To much (information) is not good.
If you're developing a one off website maintained just by you, you may find the concept of public and private functions unnecessary.
However, if you're delivering software to other people, and they're building on top of your software, it is an absolutely critical concept.
Think of it like a physical machine that has a thousand knobs and switches inside it, but is contained inside a pretty case with only a few clearly labelled knobs on the outside.
The public functions and methods are the ones you create for external parties to interact with your software.
The private functions and methods are the ones you create for your software to interact with
itself.
But, again, if it's a one-off website maintained by a single developer, these differences are less important.

Should a newly created class "start" itself during construction?

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..)

Interface reference variables

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.

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.