Page 1 of 2

Some OOP theory confusion :) [Interfaces]

Posted: Sun Sep 28, 2008 6:28 pm
by Inkyskin
Hey all - when I started working with classes I kind of jumped in with the basics, but didn't see the need to go much further. Now I'm looking at design patterns etc, and I'm confused: What is the point in using an interface?

All the tutorials I've read don't really explain the need for them, or why they are used... All they appear to do is define the functions methods used in a class - which (so far) doesn't seem to serve a real purpose...

Can anyone enlighten me? ;)

Re: Some OOP theory confusion :) [Interfaces]

Posted: Sun Sep 28, 2008 8:19 pm
by alex.barylski
Hey all - when I started working with classes I kind of jumped in with the basics, but didn't see the need to go much further
Common. I guess it's not really needed but if you don't fully understand OOP all you end up doing is classes as a namespace of sorts or giving procedural code an object wrapper, which isn't bad but it's not fully utilizing objects.
Now I'm looking at design patterns etc, and I'm confused: What is the point in using an interface?
You should probably search the forum as I am sure this has been disscussed before, but...

Interfaces are nothing more than a contract between the original implementor of a library and any future client developers looking to extend or change how a library might work.

For instance consider the simple example of a database abstraction layer.

One of the main pruposes behind a DB asbtraciton layer to to remove the dependency on a specific database engine, such as MySQL.

This is typically accomplished by injecting the database driver/engine/whatever you want to call it into the database adapter/front end.

The database drivers would typically "implement" not "inherit" the interface set forth by the developer of the original database library.

Example:

Code: Select all

interface Database_Driver{
  function getResults();
  function selectAll();
}
Then your driver class would implement the above interface and an exception is thrown whenever one of the required/contract methods are not implemented:

Code: Select all

class Database_MySQL implements Database_Driver{
  function getResults()
  {
    return 0; // Not implemented yet -- without this definition error would occur
  }
}
By "implementing" an interface you are basically saying to PHP to check the code and make sure all the required methods are implemented. Why? Because if someone later wants to swap a MySQL driver for say a SQLLite driver they know they have to implement the interface and implement each required method in order for the new SQLLite driver to work with the database library...

You would then maybe use database drivers like so:

Code: Select all

 
$dbe = new Database(new Database_Driver_MySQL($conn_params));
$dbe->selectAll();
$res = $dbe->getResults();
 
// TODO: Iterate results
 
Using an interface anyone can swap the driver for a new one and the calling code is not affected or required to be changed. Why? Because all supported methods are implemented due to the implementation of an interface.

Cheers :)

Re: Some OOP theory confusion :) [Interfaces]

Posted: Sun Sep 28, 2008 8:30 pm
by Eran
Another good example is the Iterator interface used in the SPL:

Code: Select all

 
interface Iterator extends Traversable
{
     function rewind();
     function current();
     function key();
     function next();
     function valid();
}
 
Classes implementing this interface can be traversed using some array operators, such as the foreach {} construct. This addition to the language was only possible through the use of interfaces - the only other way is inheritance based, which severely affects its usefulness.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 1:27 am
by The_Anomaly
As the GOF words of wisdom go, "Code to an interface, not an implementation."

An interface is basically just that--an interface. As was stated above, by creating an interface, you're giving your client (which could be another layer), a controlled way of accessing the properties and methods in your class. For example, you might make a domain model that has an ID in it. If you need that ID for another layer, you'll keep $id private, but you'll make a public method getID(), that allows the client to get that ID.

At least, that's how I understand an interface at a theoretical level. I don't believe that the "class1 interfaces class2" syntax is all that's too it...it's a whole concept core to encapsulation and other OOP elements.

As far as what you said about skipping the more "advanced" OOP concepts, I know exactly what you mean. As one of the other guys on this thread said, I was just making a library on steroids. i.e. a bunch of functions organized into classes with inheritance. But man, is there more to OOP than that. If you're interested in reading, check out Matt Zandstra's PHP 5 Objects, Patterns, and Practice. Almost everything I know about OOP was taught in that book--and I had already read multiple PHP books prior to it.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 1:53 am
by alex.barylski
a controlled way of accessing the properties and methods in your class. For example, you might make a domain model that has an ID in it. If you need that ID for another layer, you'll keep $id private, but you'll make a public method getID(), that allows the client to get that ID.
You can define properties in an interface? I've never even tried in PHP but I would consider that a not very good practice as member data is typically more akin to implementation level code, because it's data.

I believe an interface should be strictly the public methods, although just quickly looking over the docs it does appear to allow you specify the access control for methods...
At least, that's how I understand an interface at a theoretical level. I don't believe that the "class1 interfaces class2" syntax is all that's too it...it's a whole concept core to encapsulation and other OOP elements.
Bah you sound like a Java developer using interfaces as an argument for multiple inheritence. :P

Interfaces are not a substitute for MI the only similarity is you can implement multiple interfaces just like MI lets you inherit from multiple classes.

Honestly, interfaces are pretty simple, but like most things we as developers want to over complicate things. LOL It's actually pretty hard to remain focused on keeping simple when solving complex problems -- which computer science is all about.
But man, is there more to OOP than that.
Probably the biggest change for me was avoiding inheritence at all cost...when I began favouring composition and DI is when my code really cleaned up and a huge difference was noticed.

Object principles like OCP, etc are pretty simple too...in fact any developer who has wrote OO code for any length of time will likely use 99% of those best practices anyways (similar to design patterns). Formalizing your understanding though (and building your vocabulary) is what really makes a difference in understanding your code and code of others.

Cheers :)

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 2:34 am
by The_Anomaly
I'm ashamed to say that I can't even be compared to a java dev, because I don't even know what MI is ;)

However, when I say "interface," I don't think we're talking about the same thing. Heck, in my current project, I don't even have one interface class--only abstract ones. I'm sure that's some flaw--and I'll probably find that I'm missing something massive by not doing so. It appeared to me that interfaces and abstract classes were pretty much the same...just one is more strict than the other. I'm sure I'm wrong on that though, and should look it up.

However, when I made the above post, I was speaking mostly in terms of abstract super classes and their concrete client classes. For example, if I have an abstract superclass Client, and it has two concrete classes FemaleClient and MaleClient, I think of Client as an interface for the two (even though I defined it as abstract, not interface). As in, when I create a method that uses FemaleClient or MaleClient, I won't write it for each of them...I'll write it for the Client. So, the Client is the type I'll use, and the FemaleClient and MaleClient are what come through it--but the method calling them is totally oblivious as to which one it is. This way, the method calling them can work with both, and is not bound to either the Male or Female.

Basically, that you should hide different implementations of a class behind it's superclass. So, the client calling the implementation will accept any of the superclass' type, as long as it conforms to a certain setup.

As far as the assigning the variables in the abstract/interface class, it just made sense to me. For example, I have a Domain Model object in my current application for a video. There are two different types of video, and they both have the exact same property names, just different property values, and different methods. So, I have them both extend from the same abstract superclass, and in that superclass have all of the protected properties that a video, regardless of the kind, has.

So, I have the following:

Code: Select all

 
abstract class Video {
 protected $duration;
 protected $name;
 protected $time;
 
//...getters and setters here
 
//Varying elements of each concrete class
 abstract function encode();
 abstract function compress();
}
 
class AVideo extends Video {
//This class encodes the video as FLV, and gives another method to compress it.
}
 
class BVideo extends Video {
//This class encodes video as WMA, and gives another method to compress it
 
}
 
 
 
So the client comes along:

Code: Select all

 
 
function getVideo( Video $video ) {
 
 
 $video->encode( );//Encodes, no matter what type of video it is.
 $video->compress( ); //Compresses, no matter whta type of video it is.
 
}
 
getVideo ( new BVideo ); //Encodes and compresses as a WMV
 
getVideo( new AVideo); //Using the same client for the FLV now. This is the beauty of the interfacing...this function doesn't care whether I use flv or wmv
 
When I think about it, perhaps there are better ways of dealing with this specific problem of having two video types. I'm just using it as an example of my understanding of interfaces...without using the word interfaces once in my code. Please tell me if this is flawed, and if so, how.
Object principles like OCP, etc are pretty simple too...in fact any developer who has wrote OO code for any length of time will likely use 99% of those best practices anyways (similar to design patterns). Formalizing your understanding though (and building your vocabulary) is what really makes a difference in understanding your code and code of others.

Cheers :)
This is probably where I'm getting caught the most. I'm most definitely an amateur when it comes to OOP, and I feel that I can only learn by discussing it on here--hence I may come off as very ignorant sometimes ;) But hopefully, with time, I'll get that vocabulary and understanding

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 9:16 am
by Inkyskin
Thanks guys :) I think it kind of makes sense to me now - it's more of a guarantee that a class will have the required functions more than anything else, if I have understood correctly.

Yeah, I jumped into OOP code, but like others, most of my classes are just a collection of functions (bar the odd few). I'd like to now start exploring the theory behind real OOP principles, hence the looking into design patterns etc.

My main issue at the moment is finding the information I need - there's lots of sites that discuss the absolute basics, and others that discuss the extremes. I'm having trouble finding somewhere that really shows how OOP code can be used in everyday things, going over the intermediate level stuff.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 2:17 pm
by fredrik
pytrin wrote:This addition to the language was only possible through the use of interfaces
Not entirely true, you could use something along the lines of duck-typing/design by contract and just make every object that implements those methods iterable a´la python.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 2:18 pm
by alex.barylski
I'm ashamed to say that I can't even be compared to a java dev, because I don't even know what MI is
MI = Multiple inheritence.

Antiquated technique, probably over abused when first introduced. When working with OOP and making the analogy to the real world it makes sense as most every living organism on the planet stems from two parents. The problem is, rarely do we model live organisms in software develpment, but instead in-animate objects where the concept of inheritence doesn't really apply. A screw driver doesn't really borrow behavior from a hammer in the real world, but they are both "tools" which share some common funcitonality.
However, when I say "interface," I don't think we're talking about the same thing. Heck, in my current project, I don't even have one interface class--only abstract ones
An interface is not a class. Abstract classes and interfaces have more in common than a class and interface. The difference being an abstract class has an implemention usually.
It appeared to me that interfaces and abstract classes were pretty much the same...just one is more strict than the other. I'm sure I'm wrong on that though, and should look it up.
Similar but key difference -- see above.
As far as the assigning the variables in the abstract/interface class, it just made sense to me. For example, I have a Domain Model object in my current application for a video. There are two different types of video, and they both have the exact same property names, just different property values, and different methods. So, I have them both extend from the same abstract superclass, and in that superclass have all of the protected properties that a video, regardless of the kind, has.
That is the idea, yes.

Your abstract class should basically contain any generic implementation code. Then if nessecary you override the abstract class methods to fine tuning compression, etc. This is the key ieda behind virtual functions and polymorphic programming. It's done for you automagically in PHP but in other languages like C++ it needs to be explicitly declared as such, which is why OOP is usually even more abused in C++ than PHP.
When I think about it, perhaps there are better ways of dealing with this specific problem of having two video types.
I don't understand enough of the problem to say, but I probably wouldn't use two classes unless it's absolutely nessecary. Here is what I would do (do avoid abusing OOP).

I would first implement a base class (not abstract). When I began using conditionals to handle different file types or compression types, etc I would then consider two options:

1. Remove the conditionals from the base class and throw the file type specific implementation into a child class and derive from the abstract base class.
2. Keep the base class as is (not abstract) and use composition and inject the file type specifics into the base class -- this is what I typicall prefer.
This is probably where I'm getting caught the most. I'm most definitely an amateur when it comes to OOP, and I feel that I can only learn by discussing it on here--hence I may come off as very ignorant sometimes But hopefully, with time, I'll get that vocabulary and understanding
I don't think you can ever fully be an expert in programming as the best practices always change. MI for instance was big (and still is in C++ frameworks) and now it's an antiquated practice most OOP developers frown on.

The best way to learn is to ask questions, argue your points the best you can and hopefully receive a logical rebuttle and not some emotional reply about one's fave technqiue. Certainly it has been my conversations with others that have changed my viewpoint, not reading books.
Thanks guys I think it kind of makes sense to me now - it's more of a guarantee that a class will have the required functions more than anything else, if I have understood correctly.
I would say yes, you understand now. Although it's more common to say "contract" than "gaurantee" either works though.
Yeah, I jumped into OOP code, but like others, most of my classes are just a collection of functions (bar the odd few). I'd like to now start exploring the theory behind real OOP principles, hence the looking into design patterns etc.
Good start. Object principles are also a good bet.

http://java.sys-con.com/node/38673
http://www.objectmentor.com/resources/articles/ocp.pdf
http://en.wikipedia.org/wiki/Open/closed_principle

OCP is probably the most important principle to understand when you want to write "real" OO code.

Google Object Oriented Design and Principles. There are several moer principles/best practices which you should learn as well.
I'm having trouble finding somewhere that really shows how OOP code can be used in everyday things, going over the intermediate level stuff.
That is going to be the hard part. The problem is, most articles on OOP are written by complete newbies to it who just want to get attention, so the articles are limiting and usually inaccurate (devarticles, phpbuilder, etc). Then on the other end of things you have people like OO experts who disscuss advanced topics using weird analogies like Ducks and Shapes, which are impossible to relate to real world development when you first start out.

I would say 98% of my code base is pure objects following all best practices that are applicable. Problem is, the objects only make sense in the grand scheme of things and wouldn't serve much purpose on a single object instance, so I can't exactly write an article hilighting best practices.

I have a resultset object which is initialized with a model object which is then injected into a paginator object which is then injected into a layout object which is then initialized with about 15 different objects and altogather generates a HTML display using nothing but objects (other than my template scripts). While it's made a very clean design, alone each object makes very little sense outside of the scope of my application.

You just need to keep reading and trying new things, asking questions, learning and eventually you'll get there.

Cheers :)

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 2:52 pm
by Inkyskin
Thanks for the advice Hockey, time to start reading more :)

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 3:33 pm
by Christopher
I think designing clear, clean interfaces -- and then programming to them is a key best practice for programmers. In PHP, I think use the interface construct when you actually have a need to enforce an interface upon other programmers.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 4:43 pm
by alex.barylski
I think designing clear, clean interfaces -- and then programming to them is a key best practice for programmers. In PHP, I think use the interface construct when you actually have a need to enforce an interface upon other programmers.
Agreed. Although I use interfaces when I know that a functionality will be pluggable/extendable via modules as well. Just as a reminder to make sure methods are implemented.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 4:52 pm
by Christopher
Hockey wrote:Agreed. Although I use interfaces when I know that a functionality will be pluggable/extendable via modules as well. Just as a reminder to make sure methods are implemented.
Yep, if want to enforce a interface, whatever the reason, then that's a way to do it. Different programmers may have different reasons, but the mechanisms are the same.

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 8:50 pm
by josh
You can check which interface a class implements at run time, and treat it differently based on which interface it implements as well ( when using polymorphism.. for example through an exception if your function was passed the wrong object ).. not something that can't be done through regular subclassing but its "cleaner" through an interface
http://us3.php.net/instanceof

Re: Some OOP theory confusion :) [Interfaces]

Posted: Mon Sep 29, 2008 9:35 pm
by Christopher
jshpro2 wrote:You can check which interface a class implements at run time, and treat it differently based on which interface it implements as well ( when using polymorphism.. for example through an exception if your function was passed the wrong object ).. not something that can't be done through regular subclassing but its "cleaner" through an interface
http://us3.php.net/instanceof
This is, in my opinion, actually the only "technical" reason to use interfaces in PHP. Enforcing interfaces is a matter of opinion to some extent, because it is about how an error will be discovered and not about functionality. The area where I have seen multiple-inheritance using interfaces actually is with things like Dependency Injection systems where you want to communicate a "type" of class to the system.