Having problems understanding OOP. Public members or getters and setters? [closed] - oop

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i'm trying to learn OOP and i did read a lot of topics about OOP but I still don't fully grasp the concepts.
I'm asking for some clarification regarding that matter, in particular:
Is it fine to have public members in a class, or should I always use getters and setters?

OOP or Object Oriented Programing is a paradigm (method) of writting programs. Basically, it simplifies creating programs by considering everything as an object represented by classes.
The basic concepts of OOP (applies for all languages) are clear:
Inheritance: Object A (or class) is able to inherit from another object, let's say Object B. That means that Object A, in this case the child, will inherit the attributes and methods of object B which is in this case the parent. This concepts means that you can re-use your code.
Polymorphism: As the name indicates, it means than an object, more specifically, a method can take several forms. How? This concept goes with Inheritance. Say you have a parent class that is Animalthat has a method called talk() that prints some text, and you have two child classes respectively called dog and cat. Both child classes would inherit the method talk() from their parent class being Animal. Both dogs and cats are Animals, but they do not talk the same way. To solve this, we would re-define the method talk()in the child classes using the concept of polymorphism without needing to changing the method's name or signature.
Encapsulation: Last, understanding this concept should answer question 2 and 3. Basically, this means that each object or class will contain inside its own members (which provide data) and methods (which provide data manipulation). With this, what you are doing is binding the data with the methods in one container being the object. For example, let's take an Air Conditioner AC for short. An AC has attributes, let's say: make, model, isOn, temperature. Additionally, it encapsulates methods to manipulate the temperature: tempDown() and tempUp() to lower and raise the temperature by one degree.
What you need to understand here that, the AC's methods to lower or raise the temperature are already built inside it. It is not us people who lower or raise the temperature, sure we do press the button but that only triggers the method that does that. The functionalities themselves are build inside the AC not outside it, that is to say that the methods that manipulate the AC should be encasulated inside the AC. The attributes on the other side are supposed to be private by concept. The AC's attributes, for example the temperature, belongs to the AC itself, it should not be public. It is bad practice to set a class' attributes as public because it defies the encapsulation concept. And so only the methods encapsulated with the attributes should have access to them. If you need to edit the attributes of an object from outside the class, you can create a method that does that for you. Methods are public.
At last, regarding the use of getters and setters, there are a lot of debates about the subject, some even describe them as "Evil". If you create methods just to access the class attributes, you might as well just set them as public and spare yourself the extra lines of code. Some languages even have better ways to manage members like using properties in Python. Like I said before, attributes should remain private and should only be edited/accessed by the object itself, not from the outside. The way to do that is via the methods that will manipulate them. For example, let's say you have a bank account that has an attribute : balance. If you were to set the attributes as public or have getters/setters, it means anyone can access your balance from outside the class and change it to whatever value they like. On the other side, if you had the attributes private, the class decides what sort of data manipulations you can have via the methods. A method that would only print the balance, or that would only add money if it is extracted from another account, you can even add an extra layer of secury via logging each action inside each method.
You can add Abstraction (basically separating the declaration and implementation of code through interfaces) and Overloading to the mix. You can read more information here :
https://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm

Related

OOP: What is the correct terminology for talking about methods and attributes? Both of classes, and their instances? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Say I have a class in a programming language:
class name {
variable_name = 1;
method_name(x) {
// return something
}
}
foo = new name();
print(foo.method_name(foo.variable_name));
How correct is the following? Can we make it more correct?
If I want to talk about a specific instance of a method (foo.method_name), would I say 'the method_name-method of the object foo'? Or something else? Or does talking about the instance of a variable of method make no sense?
If I want to talk about a general object of any name, and refer to its method_name-method or variable, what would I say? Would I say 'the method_name-method/variable_name-variable of the class name?' or something else?
Thank you for your time.
Kind regards,
Marius
Talking about a specific instance of a method doesn't really make any sense as you say. Usually we talk about instances of classes - objects - and their methods. Thus one would normally talk about something like "calling method_name on foo" or simply foo dot method_name.
That's a fine way of saying it. In my experience it doesn't really matter all that much in day to day communication as the method really does the same thing anyways, just with different values in it's scope. It's what it does that really matters (e.g. accelerate() or toString()). Perhaps the most important part when talking about methods, variables etc. is communicating clearly if they happen to be static - i.e. not belonging to any given instances. In day to day speak I wouldn't make any effort to differentiate very clearly between "then we can just call accelerate on our car instance" and "the car class has a method named accelerate" (it's given that this is a non-static method) - I might however specify that "our car class has a static method to help us calculate acceleration.
In a nutshell:
Classes: (which may be instantiated to objects)
can have -
(non-static / instance) members
- public
- methods
- properties
- private
- methods
- properties
(static / class) members
- public
- methods
- properties
- private
- methods
- properties
However, methods have/can also be called messages, selectors, or behaviours (depending on the language in question, and in particular contexts.) It's occasionally considered incorrect to call them functions, however no one in their right mind should take you to task over such things. (notably the appearance of the keyword function in ECMAScript shows its level of acceptability. As a rule of thumb, the language domain would always define correctness, otherwise generally the term is fine/understandable but can lead to ambiguity.) Similarly properties are variously called, fields, attributes or variables.
An alternative name for non-static methods or properties is to call them instance methods or properties. While static methods / properties may be referred to as class methods / properties. By the way, ommitting the non-static qualifier, is usual and implicit.
As a general guideline, refer to the language under use to determine the correct terms, as they are specific to the various language cultures.
The assumption in writing this, is that there's no need to outline the scope/access differences of these class members. If that's required, I'd be happy to add a note.

In OOP what are the different meanings of interface in the different contexts they apply to [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm a bit new to object oriented programming. On my journey I have come across something that has had me confused for a few days now. It is the term "interface" and how it has different meanings in different contexts and even different programming languages. I want to understand "interface" but when I do my research I seem to get different definitions as if it has multiple meanings.
Would someone kindly give me a concise definition of interface in each context (just the main ones)?
I purchased a book called the object oriented thought process by Matt Weisfeld where some of them have been identified which are below:
Graphical user interface
The interface to a class is basically the signatures of its methods
Objective-C code can be broken up into physically separate modules called interface and impelentation
A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class
(Are there any more uses/definitions of the term interface in OOP than those identified above?)
If someone would kindly explain the different contexts of the term interface in OOP it would be highly appreciated.
Short answer:
Your 4th bullet point probably comes closest to the generally accepted notion of what OOP interfaces are: contracts between parties that need to interact with one another. Such contracts define the means (a) provided by one party, and (b) required by the other, in order to do so.
Long answer:
Very generally speaking, an interface is a thing that allows two (possibly very different) entities to interact with each other; it enables them to work together while at the same time allowing them to stay apart. The interface is the "common ground" that both parties agree on.
(Can be as simple as a door lock: Both the lock and any key able to work it must "fit together" in one place; you could call that place the interface.)
How does this general definition apply to your list?
Graphical user interface
A GUI allows humans and computer programs to interact. It does not require the computer to become fully human (and listen with ears, talk with the mouth, smile, etc.), neither does it require of the human to become a computer program itself. (UIs from past decades excluded. :)
"The interface to a class is basically the signatures of its methods"
The (publicly visible) methods and their exact signatures are the only means by which other types are going to be able to interact with that class, so in that sense, they together form that class' interface.
Also, a general description of each constructor and method is typically a part of the interface as well as a short general description of the purpose of the class and each of its methods. And of course, the name of the class itself -- pretty important.
"Objective-C code can be broken up into physically separate modules called interface and [implementation]"
I don't know Objective-C well enough to comment on that, but many languages have a module system that allows you to partition your codebase into separate, functionally independent modules. These usually don't have to expose all their types and functions to outsiders; each module may carefully declare what can be seen by other modules. As above, all that is chosen to be exposed is the "interface", because it will be the only way to interact with whatever is in the module. That "whatever is in the module" stays hidden; it's called the "implementation", and outsiders should not have to know about it.
"A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class"
This is perhaps what comes closest to the generally accepted notion of interfaces in OOP: That they are contracts between parties that want to interact. See short answer at the beginning of this question.
Basically, a Java interface allows us to describe a group of methods and their exact signatures, but it won't allow us to provide the implementation. Therefore it's a pure interface; it cannot be called directly. It only describes how one could interact with a class that actually implemented it. (The two parties do not necessarily have to be "parent" and "child".)
Ideally, an interface should not just state what one class has to offer; it should also describe what a typical consumer will need, thereby keeping the interface focused in a well-encapsulated system. (I am referring to the Single-Responsibility Principle here.)
Interface is a concept of abstraction and encapsulation. It is basically a contract you should comply to or given to ie, Interface is just a contract between two parties so that they know how they will interact with each other. An interface generally defines how you can interact with a class, the methods that it supports.
An interface contains only the signatures of the methods. The methods dont have anything neither interface can do anything. It is just a pattern.
Now in this anAbstarctMethod() is the Interface which is defined and it only has signatures but it doesnot have the implementation. Now when the class ASubClass implements the ineterface then the actual implementation is provided to the interface.
As far as Graphical user Interface is concerned I dont think that may necessarily be Object Oriented Programming. The wiki says that a graphical user interface is just a user interface through which you can interact with the electronic devices through icons and other indicators.
The Java doc has given a good example for this:-
Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the
interface between you and the electrical wiring on the other side of
its plastic casing. You press the "power" button to turn the
television on and off.
A good example from here:-
An interface is a description of the actions that an object can do...
for example when you flip a light switch, the light goes on, you don't
care how, just that it does. In Object Oriented Programming, an
Interface is a description of all functions that an object must have
in order to be an "X". Again, as an example, anything that "ACTS LIKE"
a light, should have a turn_on() method and a turn_off() method. The
purpose of interfaces is to allow the computer to enforce these
properties and to know that an object of TYPE T (whatever the
interface is ) must have functions called X,Y,Z, etc.
You may also check Why Use Interfaces?
Another powerful design technique is to have a single class implement
multiple interfaces. If you do this, you will have objects that
support multiple interfaces and, therefore, multiple behaviors. When
used together with run-time type inspection, this becomes very
powerful.
In OOP, the term "interface" means basically all the method signatures for all the messages that can be sent to objects of a class. So in Objective-C, it would be all the method declarations in the header file.
The term "Graphical User Interface" is not using the word "interface" in an OO context.
Item #2 on your list is an OO interface.
Item #3 is referring to the .h and .m files.
Item #4 refers to the keyword 'interface' in the Java language and equating it to the keyword 'protocol' in the objective-C language.
General meaning:
An Interface is essentially something that interacts with something else
For example: An interface can be with a python application and the Skype-API (thought off the top of my head xD)
An interface is a form of multiple inheritance (without the 'alleged' complications that brings) (it's a controversial subject)
OO is founded on the "is a" relationship, MI (multiple inheritance) allows an object to be several things. Interfaces define a way for them to be these things, without an implementation.
They are "what you must to _to be a _ whatever".

Does MVC break encapsulation?

Let's say I have an class to model a city. Its characteristics are the following:
It has only two properties "name" and "population", both private, that are set in the constructor.
It has getters for these properties, but not setters.
I don't want any user of this class to set the properties, I want them to use a public .edit() method.
This method needs opens up a form to input the new name of the city and population, i.e.: a view. Then, if I have a view, I would like to implement the MVC pattern, so the idea would be that the controller receives the .edit() call, renders the view, retrieves the data back, and sends it to the view so that it changes its state.
But, if I do so, I have to change the properties of the city model from private to public. So, if any user instantiates my class, she/he can directly change the properties.
So, the philosophical question: Isn't that breaking the encapsulation?
EDIT Just to make it more explicit:
This city_instance.edit() method should be the only way to mutate the object.
Besides, I see that part of my problems comes from the misunderstanding that a model is an object (you can read that on php mvc frameworks), when it is actually a different abstraction, it's a layer that groups the business logic (domain objects + I guess more things)
Disclaimer: I don't really understand where are you proposing the .edit() method to be implemented, so it would help if you could clarify that a little bit there.
The first thing to consider here is that in the bulleted list of your question you seem to imply that a City instance acts like an immutable object: it takes its instance variables in the constructor and doesn't allow anybody in the outside to change them. However, you later state that you actually want to create a way to visually edit a City instance. This two requirements are clearly going to create some tension, since they are kind of opposites.
If you go the MVC approach, by separating the view from the model you have two main choices:
Treat your City objects as immutable and, instead of editing an instance when the values are changed in the form, throw away the original object and create a new one.
Provide a way to mutate an existing City instance.
The first approach keeps your model intact if you actually consider a City as an immutable object. For the second one there are many different ways to go:
The most standard way is to provide, in the City class, a mutator. This can have the shape of independent setters for each property or a common message (I think this is the .edit() method you mentioned) to alter many properties at once by taking an array. Note that here you don't take a form object as a parameter, since models should not be aware of the views. If you want your view to take note of internal changes in the model, you use the Observer pattern.
Use "friend" classes for controllers. Some languages allow for friend classes to access an object's internals. In this case you could create a controller that is a friend class of your model that can make the connection between the model and the view without having to add mutators to your model.
Use reflection to accomplish something similar to the friend classes.
The first of this three approaches is the only language agnostic choice. Whether that breaks encapsulation or not is kind of difficult to say, since the requirements themselves would be conflicting (It would basically mean wanting to have a model separated from the view that can be altered by the user but that doesn't allow the model itself to be changed for the outside). I would however agree that separating the model from the view promotes having an explicit mutation mechanism if you want mutable instances.
HTH
NOTE: I'm referring to MVC as it applies to Web applications. MVC can apply to many kinds of apps, and it's implemented in many kinds of ways, so it's really hard to say MVC does or does not do any specific thing unless you are talking strictly about something defined by the pattern, and not a particular implementation.
I think you have a very specific view of what "encapsulation" is, and that view does not agree with the textbook definition of encapsulation, nor does it agree with the common usage of it. There is no definition of "Encapsulation" I can find that requires that there be no setters. In fact, since Setters are in and of themselves methods that be used to "edit" the object, it's kind of a silly argument.
From the Wikipedia entry (note where it says "like getter and setter"):
In general, encapsulation is one of the four fundamentals of OOP (object-oriented programming). Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing.
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Now, that's not to say that MVC doesn't break encapsulation, I'm just saying that your idea of what Encapsulation is is very specific and not particularly canonical.
Certainly, there are a number of problems that using Getters and Setters can cause, such as returning lists that you can then change directly outside of the object itself. You have to be careful (if you care) to keep your data hidden. You can also replace a collection with another collection, which is probably not what you intend.
The Law of Demeter is more relevant here than anything else.
But all of this is really just a red herring anyways. MVC is only about the GUI, and the GUI should be as simple as possible. It should have almost no logic in either the view or the controller. You should be using simple view models to deserialize your form data into a simple structure, which can the be used to apply to any business architecture you like (if you don't want setters, then create your business layer with objects that don't use setters and use mutattors.).
There is little need for complex architecture in the UI layer. The UI layer is more of a boundary and gateway that translates the flat form and command nature of HTTP to whatever business object model you choose. As such, it's not going to be purely OO at the UI level, because HTTP isn't.
This is called an Impedance Mismatch, which is often associated with ORM's, because Object models do not map easily to relational models. The same is true of HTTP to Business objects. You can think of MVC as a corollary to an ORM in that respect.

When subclassing an object, what is the appropriate method to handle functions that don't make sense on the child?

Before I jump into the meat of the question, let me note that this is a purely theoretical query. I'm not interested in this for practical reasons, I'm interested in the underlying OOP theory on how to handle this type of situation.
In a project I'm working on, I have two closely related classes. One is the generic 'user' class. The other is subclassed, and adds additional features used by certain users -- for a generic example, think a 'moderator' class.
How do I handle public methods that are available on the user class that don't make sense for the child to have called?
For example, it makes perfect sense to call User::getUserWithId(id) (this method retrieves data from the DB and initializes and returns the user class with that data); it doesn't make as much sense (if any) to use that method with the moderator class.
Should I just ignore it -- if a user calls moderator::getUserWithId(id), they're still getting a user, exactly what they asked for. Should I override it to return a moderator, despite the method name? Or is there something in OOP land I'm not familiar with that lets me 'block' the call?
If you have methods in your base class that don't make sense in your subclass, then I think you need to re-evaluate if you should model these classes via an inheritance relationship. Needing to hide members of a base class in a subclass is a red flag that indicates modeling this via an inheritance relationship is problematic.
An inheritance relationship should indicate an "is a" relationship. For your example, a moderator object "is a" user object and thus should have the same methods and properties as the user object. If it does not, then it would appear that it does not have a true inheritance relationship with its base user class.
In this case, you might want to consider using interfaces instead of inheritance. You can factor the common functionality between the User and Moderator classes into an interface. If there is common code that they can share, then you can use composition to achieve this, by creating a common implementation of the interface and then passing it to the classes that need to reuse this code. For further information, see here and here.
As the author in the second link above puts it:
Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.
Does TypeB only want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
From your need to hide a member of the base class, it seems that you are in the second category, and might want to explore using composition and an interface.
Yesterday I left a response, that somehow got lost. I think, #Joe Alfano has a very good explanation that addresses your "theoretical" and also particular questions.
Beside that, In my opinion, one source of your problem might be that you are doing database access in your Domain Object. In general, unless there is a compelling reason, this is not a good practice. If you remove that database access into a separate layer like Data Access Layer (DAL) this problem goes away. You won't have User::getUserWithId(id) things in your classes, they will be handled in DAL. Like
class UserDao {
User getById(id)
}
Class ModeratorDao {
Moderator getById(id)
}
If you go with DAL-like approach, then you will also find ways to re-factoring code, which is a separate thing.

Why would I want to use Interfaces? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.
One specific example: interfaces are a good way of specifying a contract that other people's code must meet.
If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code.
Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-)
Another specific example: two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs.
The key point is that interfaces provide a layer of abstraction so that you can write code that is ignorant of unnecessary details.
The canonical example used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the IComparable interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.
The easiest way of understanding interfaces is that they allow different objects to expose COMMON functionality. This allows the programmer to write much simplier, shorter code that programs to an interface, then as long as the objects implement that interface it will work.
Example 1:
There are many different database providers, MySQL, MSSQL, Oracle, etc. However all database objects can DO the same things so you will find many interfaces for database objects. If an object implements IDBConnection then it exposes the methods Open() and Close(). So if I want my program to be database provider agnostic, I program to the interface and not to the specific providers.
IDbConnection connection = GetDatabaseConnectionFromConfig()
connection.Open()
// do stuff
connection.Close()
See by programming to an interface (IDbconnection) I can now SWAP out any data provider in my config but my code stays the exact same. This flexibility can be extremely useful and easy to maintain. The downside to this is that I can only perform 'generic' database operations and may not fully utilize the strength that each particular provider offers so as with everything in programming you have a trade off and you must determine which scenario will benefit you the most.
Example 2:
If you notice almost all collections implement this interface called IEnumerable. IEnumerable returns an IEnumerator which has MoveNext(), Current, and Reset(). This allows C# to easily move through your collection. The reason it can do this is since it exposes the IEnumerable interface it KNOWS that the object exposes the methods it needs to go through it. This does two things. 1) foreach loops will now know how to enumerate the collection and 2) you can now apply powerful LINQ exprssions to your collection. Again the reason why interfaces are so useful here is because all collections have something in COMMON, they can be moved through. Each collection may be moved through a different way (linked list vs array) but that is the beauty of interfaces is that the implementation is hidden and irrelevant to the consumer of the interface. MoveNext() gives you the next item in the collection, it doesn't matter HOW it does it. Pretty nice, huh?
Example 3:
When you are designing your own interfaces you just have to ask yourself one question. What do these things have in common? Once you find all the things that the objects share, you abstract those properties/methods into an interface so that each object can inherit from it. Then you can program against several objects using one interface.
And of course I have to give my favorite C++ polymorphic example, the animals example. All animals share certain characteristics. Lets say they can Move, Speak, and they all have a Name. Since I just identified what all my animals have in common and I can abstract those qualities into the IAnimal interface. Then I create a Bear object, an Owl object, and a Snake object all implementing this interface. The reason why you can store different objects together that implement the same interface is because interfaces represent an IS-A replationship. A bear IS-A animal, an owl IS-A animal, so it makes since that I can collect them all as Animals.
var animals = new IAnimal[] = {new Bear(), new Owl(), new Snake()} // here I can collect different objects in a single collection because they inherit from the same interface
foreach (IAnimal animal in animals)
{
Console.WriteLine(animal.Name)
animal.Speak() // a bear growls, a owl hoots, and a snake hisses
animal.Move() // bear runs, owl flys, snake slithers
}
You can see that even though these animals perform each action in a different way, I can program against them all in one unified model and this is just one of the many benefits of Interfaces.
So again the most important thing with interfaces is what do objects have in common so that you can program against DIFFERENT objects in the SAME way. Saves time, creates more flexible applications, hides complexity/implementation, models real-world objects / situations, among many other benefits.
Hope this helps.
One typical example is a plugin architecture. Developer A writes the main app, and wants to make certain that all plugins written by developer B, C and D conform to what his app expects of them.
Interfaces define contracts, and that's the key word.
You use an interface when you need to define a contract in your program but you don't really care about the rest of the properties of the class that fulfills that contract as long as it does.
So, let's see an example. Suppose you have a method which provides the functionality to sort a list. First thing .. what's a list? Do you really care what elements does it holds in order to sort the list? Your answer should be no... In .NET (for example) you have an interface called IList which defines the operations that a list MUST support so you don't care the actual details underneath the surface.
Back to the example, you don't really know the class of the objects in the list... neither you care. If you can just compare the object you might as well sort them. So you declare a contract:
interface IComparable
{
// Return -1 if this is less than CompareWith
// Return 0 if object are equal
// Return 1 if CompareWith is less than this
int Compare(object CompareWith);
}
that contract specify that a method which accepts an object and returns an int must be implemented in order to be comparable. Now you have defined an contract and for now on you don't care about the object itself but about the contract so you can just do:
IComparable comp1 = list.GetItem(i) as IComparable;
if (comp1.Compare(list.GetItem(i+1)) < 0)
swapItem(list,i, i+1)
PS: I know the examples are a bit naive but they are examples ...
When you need different classes to share same methods you use Interfaces.
Interfaces are absolutely necessary in an object-oriented system that expects to make good use of polymorphism.
A classic example might be IVehicle, which has a Move() method. You could have classes Car, Bike and Tank, which implement IVehicle. They can all Move(), and you could write code that didn't care what kind of vehicle it was dealing with, just so it can Move().
void MoveAVehicle(IVehicle vehicle)
{
vehicle.Move();
}
The pedals on a car implement an interface. I'm from the US where we drive on the right side of the road. Our steering wheels are on the left side of the car. The pedals for a manual transmission from left to right are clutch -> brake -> accelerator. When I went to Ireland, the driving is reversed. Cars' steering wheels are on the right and they drive on the left side of the road... but the pedals, ah the pedals... they implemented the same interface... all three pedals were in the same order... so even if the class was different and the network that class operated on was different, i was still comfortable with the pedal interface. My brain was able to call my muscles on this car just like every other car.
Think of the numerous non-programming interfaces we can't live without. Then answer your own question.
Imagine the following basic interface which defines a basic CRUD mechanism:
interface Storable {
function create($data);
function read($id);
function update($data, $id);
function delete($id);
}
From this interface, you can tell that any object that implements it, must have functionality to create, read, update and delete data. This could by a database connection, a CSV file reader, and XML file reader, or any other kind of mechanism that might want to use CRUD operations.
Thus, you could now have something like the following:
class Logger {
Storable storage;
function Logger(Storable storage) {
this.storage = storage;
}
function writeLogEntry() {
this.storage.create("I am a log entry");
}
}
This logger doesn't care if you pass in a database connection, or something that manipulates files on disk. All it needs to know is that it can call create() on it, and it'll work as expected.
The next question to arise from this then is, if databases and CSV files, etc, can all store data, shouldn't they be inherited from a generic Storable object and thus do away with the need for interfaces? The answer to this is no... not every database connection might implement CRUD operations, and the same applies to every file reader.
Interfaces define what the object is capable of doing and how you need to use it... not what it is!
Interfaces are a form of polymorphism. An example:
Suppose you want to write some logging code. The logging is going to go somewhere (maybe to a file, or a serial port on the device the main code runs on, or to a socket, or thrown away like /dev/null). You don't know where: the user of your logging code needs to be free to determine that. In fact, your logging code doesn't care. It just wants something it can write bytes to.
So, you invent an interface called "something you can write bytes to". The logging code is given an instance of this interface (perhaps at runtime, perhaps it's configured at compile time. It's still polymorphism, just different kinds). You write one or more classes implementing the interface, and you can easily change where logging goes just by changing which one the logging code will use. Someone else can change where logging goes by writing their own implementations of the interface, without changing your code. That's basically what polymorphism amounts to - knowing just enough about an object to use it in a particular way, while allowing it to vary in all the respects you don't need to know about. An interface describes things you need to know.
C's file descriptors are basically an interface "something I can read and/or write bytes from and/or to", and almost every typed language has such interfaces lurking in its standard libraries: streams or whatever. Untyped languages usually have informal types (perhaps called contracts) that represent streams. So in practice you almost never have to actually invent this particular interface yourself: you use what the language gives you.
Logging and streams are just one example - interfaces happen whenever you can describe in abstract terms what an object is supposed to do, but don't want to tie it down to a particular implementation/class/whatever.
There are a number of reasons to do so. When you use an interface, you're ready in the future when you need to refactor/rewrite the code. You can also provide an sort of standardized API for simple operations.
For example, if you want to write a sort algorithm like the quicksort, all you need to sort any list of objects is that you can successfuuly compare two of the objects. If you create an interface, say ISortable, than anyone who creates objects can implement the ISortable interface and they can use your sort code.
If you're writing code that uses a database storage, and you write to an storage interface, you can replace that code down the line.
Interfaces encourage looser coupling of your code so that you can have greater flexibility.
In an article in my blog I briefly describe three purposes interfaces have.
Interfaces may have different
purposes:
Provide different implementations for the same goal. The typical example
is a list, which may have different
implementations for different
performance use cases (LinkedList,
ArrayList, etc.).
Allow criteria modification. For example, a sort function may accept a
Comparable interface in order to
provide any kind of sort criteria,
based on the same algorithm.
Hide implementation details. This also makes it easier for a user to
read the comments, since in the body
of the interface there are only
methods, fields and comments, no long
chunks of code to skip.
Here's the article's full text: http://weblogs.manas.com.ar/ary/2007/11/
The best Java code I have ever seen defined almost all object references as instances of interfaces instead of instances of classes. It is a strong sign of quality code designed for flexibility and change.
As you noted, interfaces are good for when you want to force someone to make it in a certain format.
Interfaces are good when data not being in a certain format can mean making dangerous assumptions in your code.
For example, at the moment I'm writing an application that will transform data from one format in to another. I want to force them to place those fields in so I know they will exist and will have a greater chance of being properly implemented. I don't care if another version comes out and it doesn't compile for them because it's more likely that data is required anyways.
Interfaces are rarely used because of this, since usually you can make assumptions or don't really require the data to do what you need to do.
An interface, defines merely the interface. Later, you can define method (on other classes), which accepted interfaces as parameters (or more accurately, object which implement that interface). This way your method can operate on a large variety of objects, whose only commonality is that they implement that interface.
First, they give you an additional layer of abstraction. You can say "For this function, this parameter must be an object that has these methods with these parameters". And you probably want to also set the meaning of these methods, in somehow abstracted terms, yet allowing you to reason about the code. In duck-typed languages you get that for free. No need for explicit, syntax "interfaces". Yet you probably still create a set of conceptual interfaces, something like contracts (like in Design by Contract).
Furthermore, interfaces are sometimes used for less "pure" purposes. In Java, they can be used to emulate multiple inheritance. In C++, you can use them to reduce compile times.
In general, they reduce coupling in your code. That's a good thing.
Your code may also be easier to test this way.
Let's say you want to keep track of a collection of stuff. Said collections must support a bunch of things, like adding and removing items, and checking if an item is in the collection.
You could then specify an interface ICollection with the methods add(), remove() and contains().
Code that doesn't need to know what kind of collection (List, Array, Hash-table, Red-black tree, etc) could accept objects that implemented the interface and work with them without knowing their actual type.
In .Net, I create base classes and inherit from them when the classes are somehow related. For example, base class Person could be inherited by Employee and Customer. Person might have common properties like address fields, name, telephone, and so forth. Employee might have its own department property. Customer has other exclusive properties.
Since a class can only inherit from one other class in .Net, I use interfaces for additional shared functionality. Sometimes interfaces are shared by classes that are otherwise unrelated. Using an interface creates a contract that developers will know is shared by all of the other classes implementing it. I also forces those classes to implement all of its members.
In C# interfaces are also extremely useful for allowing polymorphism for classes that do not share the same base classes. Meaning, since we cannot have multiple inheritance you can use interfaces to allow different types to be used. It's also a way to allow you to expose private members for use without reflection (explicit implementation), so it can be a good way to implement functionality while keeping your object model clean.
For example:
public interface IExample
{
void Foo();
}
public class Example : IExample
{
// explicit implementation syntax
void IExample.Foo() { ... }
}
/* Usage */
Example e = new Example();
e.Foo(); // error, Foo does not exist
((IExample)e).Foo(); // success
I think you need to get a good understand of design patterns so see there power.
Check out
Head First Design Patterns