Abstract classes and Interfaces
Moderator: General Moderators
Abstract classes and Interfaces
Hey,
I'm currently reading this book for the second time.
I get the idea with abstract classes and last night I started to understand what interfaces might be useful for.
Though I would apreciate a couple of more examples to give me an idea how to implement it in my code.
If I understand the concept correctly, interfaces might be used to let your classes use methods that might be a little more general.
Say I have a couple of classes.
(from the book pretty much)
product (abstract)
- cdproduct (child)
- bookproduct (child)
The use of an interface in this example would be a couple of methods useful for these children but not specifict for a cd- or bookproduct?
Which mean my interface might be useful for other classes not related to product. If my methods are too specific they would belong to my product classes?
I'm currently reading this book for the second time.
I get the idea with abstract classes and last night I started to understand what interfaces might be useful for.
Though I would apreciate a couple of more examples to give me an idea how to implement it in my code.
If I understand the concept correctly, interfaces might be used to let your classes use methods that might be a little more general.
Say I have a couple of classes.
(from the book pretty much)
product (abstract)
- cdproduct (child)
- bookproduct (child)
The use of an interface in this example would be a couple of methods useful for these children but not specifict for a cd- or bookproduct?
Which mean my interface might be useful for other classes not related to product. If my methods are too specific they would belong to my product classes?
Re: Abstract classes and Interfaces
Say you had a product
->isTieredPrice()
->getPriceTiersAsArray()
->getLowestPrice()
->getMedianPrice()
->getPriceSimple()
->getPriceObject()
etc...
(lets assume this product has really complex pricing features). Anywhere you are working with a $product object, lets say from inside a CreditCard object (looking at the price) you are going to need these price methods. Instead of asking for a Product object, you make an interface that defines only methods relevant to price, and ask for that interface. Then your Credit Card object can work with things that are not products, as long as the implement the right interface.
Now lets say your product has more methods,
->getShippingAllowed
->getShippingTypes
->getSHippingWhatever
etc...
you'd create a "shippable" interface and also make the product implement that interface. Now lets say you have a "Shipper" class that is going to be used whenever you are shipping products, you make it work with this interface:
__construct( My_Shippable_Interface $shippable)
Now anyone implements the different ->getShipping methods can write a "plugin" for your shipping application, where as if you had asked for a Product instead of the Shippable interface, they would have had to figure out how the hell they are supposed to address the 7 "bulky" price methods when their plugin has nothing to do with pricing.
The other benefit is that even though your product now has 10+ methods, your code hinting inside the shipping application and code completion only shows you the methods you are interested in. The 3 "shipping methods" which define the "narrow interface".
Now another programmer can add a Subscription object, make it implement the "price" interface and just plug that into your system, without having to modify the credit card processing code. The design is decoupled. The credit card only cares about an "interface", not a specific Product object.
Think of it like a USB port on your computer. That USB "interface" defines a contract, allowing a whole myriad of "aftermarket" functionality (printers, mice, keyboards). In your application the interface allows for people to write "extensions" to the code a lot easier.
Now the other nice thing is whenever you CreditCard and Shipper classes change, you can update the interface. PHP won't even let the code "compile" until all the classes that implemented that interface are updated to "pass" the interface. PHP really enforces it like a contract.
->isTieredPrice()
->getPriceTiersAsArray()
->getLowestPrice()
->getMedianPrice()
->getPriceSimple()
->getPriceObject()
etc...
(lets assume this product has really complex pricing features). Anywhere you are working with a $product object, lets say from inside a CreditCard object (looking at the price) you are going to need these price methods. Instead of asking for a Product object, you make an interface that defines only methods relevant to price, and ask for that interface. Then your Credit Card object can work with things that are not products, as long as the implement the right interface.
Now lets say your product has more methods,
->getShippingAllowed
->getShippingTypes
->getSHippingWhatever
etc...
you'd create a "shippable" interface and also make the product implement that interface. Now lets say you have a "Shipper" class that is going to be used whenever you are shipping products, you make it work with this interface:
__construct( My_Shippable_Interface $shippable)
Now anyone implements the different ->getShipping methods can write a "plugin" for your shipping application, where as if you had asked for a Product instead of the Shippable interface, they would have had to figure out how the hell they are supposed to address the 7 "bulky" price methods when their plugin has nothing to do with pricing.
The other benefit is that even though your product now has 10+ methods, your code hinting inside the shipping application and code completion only shows you the methods you are interested in. The 3 "shipping methods" which define the "narrow interface".
Now another programmer can add a Subscription object, make it implement the "price" interface and just plug that into your system, without having to modify the credit card processing code. The design is decoupled. The credit card only cares about an "interface", not a specific Product object.
Think of it like a USB port on your computer. That USB "interface" defines a contract, allowing a whole myriad of "aftermarket" functionality (printers, mice, keyboards). In your application the interface allows for people to write "extensions" to the code a lot easier.
Now the other nice thing is whenever you CreditCard and Shipper classes change, you can update the interface. PHP won't even let the code "compile" until all the classes that implemented that interface are updated to "pass" the interface. PHP really enforces it like a contract.
Last edited by josh on Mon Feb 08, 2010 4:55 am, edited 2 times in total.
- PHPHorizons
- Forum Contributor
- Posts: 175
- Joined: Mon Sep 14, 2009 11:38 pm
Re: Abstract classes and Interfaces
(A reply was posted while I was typing mine. If I repeated what was said, or what I say conflicts, I haven't read the previous post)
Interfaces are all about making a contract with the world. The interface guarantees that the world can interface with your object using the methods outlined in the interface.
A real world example of interfaces are every day appliances like toasters and dvd players.
Every button/lever/dial/etc on those devices is akin to a method listed in an interface. The user of those devices is not expected to know anything about how they work. The user simply needs to know that calling a method will have a certain affect. The user may need to be schooled in the use of the device, but only so far as learning about it's public functions.
So, your interfaces should follow that pattern.
It should be noted that 99.9% of the time, the interface does not add functionality. In almost every case, only the built in interfaces add functionality to classes. Custom interfaces almost never do. And interfaces, should not add functionality.
Hope that helps.
Interfaces are all about making a contract with the world. The interface guarantees that the world can interface with your object using the methods outlined in the interface.
A real world example of interfaces are every day appliances like toasters and dvd players.
Every button/lever/dial/etc on those devices is akin to a method listed in an interface. The user of those devices is not expected to know anything about how they work. The user simply needs to know that calling a method will have a certain affect. The user may need to be schooled in the use of the device, but only so far as learning about it's public functions.
So, your interfaces should follow that pattern.
It should be noted that 99.9% of the time, the interface does not add functionality. In almost every case, only the built in interfaces add functionality to classes. Custom interfaces almost never do. And interfaces, should not add functionality.
Hope that helps.
Re: Abstract classes and Interfaces
Very nice examples, thank you boys.
Re: Abstract classes and Interfaces
I hate the term "Contract" when in context of describing an interface. It's nothing of the sort, well, at least not to the extent many like to think (and thus describe) they are. The *only* thing they guarantee is that the object implementing them has methods with the same signature, it does not guarantee behaviour. It's also partly a "solution" for multiple-inheritance.
Type-strict are fallout from lazy compilers, because these compilers are incapable of handling method calls on objects, without knowing in advance that the object can handle the method call, because of the undue fear of a run-time error. So we have some languages that will refuse to compile if we have not specified what type an object is. Java is to blame here, and PHP (developers) for trying so damn hard to be Java and insist on using type-strict code.
Thus, to loosen this heinous restraint of lazy compilers, we have Interfaces.
Type-strict are fallout from lazy compilers, because these compilers are incapable of handling method calls on objects, without knowing in advance that the object can handle the method call, because of the undue fear of a run-time error. So we have some languages that will refuse to compile if we have not specified what type an object is. Java is to blame here, and PHP (developers) for trying so damn hard to be Java and insist on using type-strict code.
Thus, to loosen this heinous restraint of lazy compilers, we have Interfaces.
-
alex.barylski
- DevNet Evangelist
- Posts: 6267
- Joined: Tue Dec 21, 2004 5:00 pm
- Location: Winnipeg
Re: Abstract classes and Interfaces
Why would an interface have to enforce a behavior before it becomes contract?
In compiled languages, this is the case, as the method signatures also include the return types, etc. So indeed an interface in a strictly typed language like C++ is essentially a contract. Who cares about the implementation and behavior, if you know you are calling a method with 3 arguments, each integers and a single return type of boolean, the behavior is strictly enforced, short of enforcing exceptions I suppose.
In PHP the term contract is a little more vague, as parameter types are more dyanmic and are return types, etc. It really only enforces a parameter sequence, or at least count and method name. Still a contract, IMO, but more like contract between you and a small business, rather than a bank or large corporation. The contract is easier to break from.
Cheers,
Alex
In compiled languages, this is the case, as the method signatures also include the return types, etc. So indeed an interface in a strictly typed language like C++ is essentially a contract. Who cares about the implementation and behavior, if you know you are calling a method with 3 arguments, each integers and a single return type of boolean, the behavior is strictly enforced, short of enforcing exceptions I suppose.
In PHP the term contract is a little more vague, as parameter types are more dyanmic and are return types, etc. It really only enforces a parameter sequence, or at least count and method name. Still a contract, IMO, but more like contract between you and a small business, rather than a bank or large corporation. The contract is easier to break from.
Cheers,
Alex
Re: Abstract classes and Interfaces
Your method with 3 integers and return type boolean still does not enforce behaviour. It only enforces method signature. The fact that interfaces are being bandied about as "Behaviour Contracts" is utterly false.
"Contract" satisfied.. behaviour? erm.
But this is still irrelevant.. all this is there to do, is to work-around the lazy compiler..
Code: Select all
interface ISomething
{
bool doSomething(int one, int two, int three);
}
public class Something : ISomething
{
public bool doSomething(int one, int two, int three)
{
return false;
}
}But this is still irrelevant.. all this is there to do, is to work-around the lazy compiler..
Re: Abstract classes and Interfaces
I don't think anyone was saying they are behavior contracts. They are interface contracts. That's why they're called interfaces. The idea is you define a interface, so that later when you add/change behavior you enforce a consistent interface.
Behavior contracts, if there's such a term, would have to be Unit Tests. Those are what you want to pin down behavior itself.
Interfaces, if nothing else, are useful for documentation value like I said. Its soo much easier to have lots of small interface, and worry about 5 or 6 methods for a given interface, rather then having to look at a class with 100 methods on it.
Behavior contracts, if there's such a term, would have to be Unit Tests. Those are what you want to pin down behavior itself.
Interfaces, if nothing else, are useful for documentation value like I said. Its soo much easier to have lots of small interface, and worry about 5 or 6 methods for a given interface, rather then having to look at a class with 100 methods on it.
- PHPHorizons
- Forum Contributor
- Posts: 175
- Joined: Mon Sep 14, 2009 11:38 pm
Re: Abstract classes and Interfaces
A class that implements an interface must implement every method listed in that interface. It has no choice. It is a contractual obligation.
An object interfacing with an object that implements a particular interface is guaranteed by said contractual obligation that all methods of the interface are implemented, even if those methods throw a "notSupportedException" exception.
In other words, the object is guaranteed to be calling methods that exist. It's really that simple and shouldn't be overcomplicated.
To the question of multiple inheritance, since custom interfaces are only a contractual obligation to implement methods, it is not multiple inheritance. The multiple inheritance comes into play when implementing interfaces which have "magic" and "built in" functionality granted to it by the programming language. Those go beyond just being an interface. They're great to use, and they do provide some multiple inheritance, but strictly speaking, it's not the interface that does that, it is the magic functionality added to the interface.
Cheers
PS And I agree 100% with what josh said
An object interfacing with an object that implements a particular interface is guaranteed by said contractual obligation that all methods of the interface are implemented, even if those methods throw a "notSupportedException" exception.
In other words, the object is guaranteed to be calling methods that exist. It's really that simple and shouldn't be overcomplicated.
To the question of multiple inheritance, since custom interfaces are only a contractual obligation to implement methods, it is not multiple inheritance. The multiple inheritance comes into play when implementing interfaces which have "magic" and "built in" functionality granted to it by the programming language. Those go beyond just being an interface. They're great to use, and they do provide some multiple inheritance, but strictly speaking, it's not the interface that does that, it is the magic functionality added to the interface.
Cheers
PS And I agree 100% with what josh said
-
alex.barylski
- DevNet Evangelist
- Posts: 6267
- Joined: Tue Dec 21, 2004 5:00 pm
- Location: Winnipeg
Re: Abstract classes and Interfaces
I didn't say anything about behavioral contracts, did I? If I did, that was not my intent. They are interface contracts to ensure two components (or whatever) can effectively communicate, nothing more. It enforces plug and play development.Your method with 3 integers and return type boolean still does not enforce behaviour. It only enforces method signature. The fact that interfaces are being bandied about as "Behaviour Contracts" is utterly false.
If you want to enforce behavior, then I guess your best bet would be to run BDD specs against your classes, etc.
Not sure I follow how or why a complier has anything to do with interfaces?all this is there to do, is to work-around the lazy compiler..
Cheers,
Alex
Re: Abstract classes and Interfaces
In dynamically typed languages one side effect of using an interface is you get a "compile" error rather than finding out at run time it didn't implement the method. But like everyone is saying that is really what Automated Behavior Verification (Tests or BDD SPecs) is for.PCSpectra wrote:Not sure I follow how or why a complier has anything to do with interfaces?all this is there to do, is to work-around the lazy compiler..
@papa
Try to think of interfaces as also a way to keep track of and/control code duplication
Re: Abstract classes and Interfaces
You didn't, but it has been bandied about the web as a behaviour contract, MS do it all the time, and I have seen it on this forum a few times before.PCSpectra wrote:I didn't say anything about behavioral contracts, did I? If I did, that was not my intent. They are interface contracts to ensure two components (or whatever) can effectively communicate, nothing more. It enforces plug and play development.Your method with 3 integers and return type boolean still does not enforce behaviour. It only enforces method signature. The fact that interfaces are being bandied about as "Behaviour Contracts" is utterly false.
I've already explained, sorry if I have done so poorly.PCSpectra wrote:If you want to enforce behavior, then I guess your best bet would be to run BDD specs against your classes, etc.
Not sure I follow how or why a complier has anything to do with interfaces?all this is there to do, is to work-around the lazy compiler..
Cheers,
Alex
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Abstract classes and Interfaces
I think it is a little disingenuous to use the fuzzy term "contract" which has a broader design meaning. Implementing an interface enforces that interface on a any class that implements it. And PHP allows multiple interface inheritance, but not multiple implementation inheritance.
(#10850)
Re: Abstract classes and Interfaces
If we go back to the example with "advanced pricing features".Jenk wrote:I hate the term "Contract" when in context of describing an interface. It's nothing of the sort, well, at least not to the extent many like to think (and thus describe) they are. The *only* thing they guarantee is that the object implementing them has methods with the same signature, it does not guarantee behaviour. It's also partly a "solution" for multiple-inheritance.
When creating my interface I only define methods that should be used. I got the impression that interfaces not only defined the methods but also implemented behavior. But that's wrong.
I'm still too stupid to understand the concept fully.
If the interface is only a shell, it's pretty much the same as an abstract class, but adds no behavior to my methods which I can do in an abstract class.
Sure it forces the classes that implements the interface to define my advanced pricing methods, but they can be completely different, and wouldn't that mean code duplication if I want to force the same calculations over and over in different classes?
If I want to decouple my pricing features and reuse the same calculations that I have made, I would need to make a class "advanced pricing features" and then use that class in my pricing, shipping classes?
gaah I'm confused. I'm obviously missing something.
My first thought was to use an interface as a user input validator just as an example:
I have a User class that inserts and edit data. Implements an interface that "cleans" the data (if age not number or textarea too long methods etc). And I could then use that same interface on my admin class and visitor class.
But that's not the way to use interfaces I guess.
Re: Abstract classes and Interfaces
Basically my point boils down to: In languages where you are forced to use strict type (Java, C#, etc.) Interfaces are a god send and woe be tide anyone who doesn't use them. In dynamic languages (PHP for example), and my in experience, it will only cause restrictions and problems. 
Where dynamic typing is possible, it should be used. If it can't, interfaces should.
Where dynamic typing is possible, it should be used. If it can't, interfaces should.