SitePoint Sponsor

User Tag List

Results 1 to 16 of 16
  1. #1
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb Uses of Interface

    Hi everyone.

    I have known OOP for quite a while now, and I came across a thread talking about design patterns - which made me go find a tutorial on them: http://www.ibm.com/developerworks/li...p-designptrns/

    So, I get them, understand them and I'm already implementing them. But what I don't get is "interface". I understand that it defines the functions which a class uses, but what's the point?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  2. #2
    SitePoint Addict Jasper Bekkers's Avatar
    Join Date
    May 2007
    Location
    The Netherlands
    Posts
    282
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Interface are useful because you decouple the interface of a class form its implementation. That comes down to your code not making any assumptions about the class that it's currently using. Also, it's often preferred to normal inheritance because you don't make assumptions about the derived classes in you base class.

    In terms of networking, an interface is to a protocol what your class is to the client or server. The protocol states what is possible, but the client and server actually implement those features. It's a form of decoupling where you don't care how stuff is executed as long as it gets done.
    Design patterns: trying to do Smalltalk in Java.
    I blog too, you know.

  3. #3
    Resident Code Monkey Chris Corbyn's Avatar
    Join Date
    Nov 2005
    Location
    Melbourne, Australia
    Posts
    713
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To put it simply without interfaces all behaviour is concretely defined in the class. With interfaces the behaviour is defined in the interface. Why is that important? Because as the last user just said it decouples your design from your implementation.

    It's one of those things that just kind of "clicks" after a while.

    Take this example (I steal the scenario from a design tutorial at JavaRanch):

    PHP Code:
    class StandardEngine {
      function 
    start()
      function 
    stop()
      function 
    injectFuel()
    }

    class 
    Car {
      private 
    $engine;
      public function 
    __construct() {
         
    $this->engine = new StandardEngine();
      }
      
      
    // ... snip ....
    }

    $car = new Car(); 
    Ok, so you got yourself a car to sell and it's got the standard engine. Great, it drives.

    Now you want a car with a FastEngine instead. How do you do it?

    Modify the class? Nope.

    Injecting the dependency (a car *needs* an engine) is a better way to go:

    PHP Code:
    interface Engine {
      function 
    start()
      function 
    stop()
      function 
    injectFuel()
    }

    class 
    StandardEngine implements Engine {
    }

    class 
    FastEngine implements Engine {

    Now your interface tells you what methods an Engine provides in its public API so you know you can *guarantee* any class implementing the Engine interface will provide those methods.

    PHP Code:
    class Car {
      private 
    $engine;
      public function 
    __construct(Engine $engine) {
        
    $this->engine $engine;
      }

      
    // ... snip ...
    }

    //Our orignal design equivalent
    $car = new Car(new StandardEngine());

    //Our fatser car. Same behaviour, different underlying implementation
    $car = new Car(new FastEngine()); 
    You could do the same thing without interfaces but using interfaces just adds a level of reassurance that your injected object really does what you think it does

  4. #4
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ah, so it allows classes to process differently, however can be accessed in the same way?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  5. #5
    Resident Code Monkey Chris Corbyn's Avatar
    Join Date
    Nov 2005
    Location
    Melbourne, Australia
    Posts
    713
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Ah, so it allows classes to process differently, however can be accessed in the same way?
    Bang on!

  6. #6
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But also don't forget about duck typing!

  7. #7
    ☆★☆★ silver trophy vgarcia's Avatar
    Join Date
    Jan 2002
    Location
    in transition
    Posts
    21,235
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Interfaces are useful when:

    1. You're building an application from the top down and you're an architect working with programmers doing the actual implementation under you.

    2. You're defining specs for something other people should be building (i.e. defining ECMAScript/Javascript for browsers and other software to implement on their own).

    For most small/midsized apps I'd say they're unnecessary and you should just build the class.

  8. #8
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Am I right in thinking Interfaces are also useful when upgrading classes - to boost your memory on what they do?

    Also, commenting functions declared in the interface would be handy - so when implementing it with classes, you know what it's meant for, and what it should return.

    So, really, it's more of a programmer's guide than a program's rules?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  9. #9
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes - basically it's just documentation. In php4 I'd often do this. The "interface" (just a class with empty methods) is handy for mocking.

    PHP Code:
    class Foo {
        function 
    a() {}
    }
    class 
    Bar // implements Foo
        
    function a() {
            ...
            ...
        }
    }
    class 
    Quark // implements Foo
        
    function a() {
            ...
            ...
        }

    As a rule I'm dead against anal-retentive java baggage in php but you might as well define a proper interface (ie with the interface keyword). It doesn't create any extra code. At the same time I've still got lots of "php4 interfaces" and usually there's no reason to take time out to update them.

    However there are times when you really must have a proper interface. Sometimes code needs to know something about itself for example a dependency injection container like Phemto uses type hints and reflection to fill dependencies. Since an interface acts like a label for a family of classes, code can depend on the interface and you can tweak behaviour easily by configuring the container with different implementations.

    PHP Code:
    // somewhere, configure the container with a concrete implementation:
    $injector->register('Bar');

    // the code depends on an interface - doesn't care about the implementation
    $foo $injector->instantiate('Foo'); 
    Last edited by McGruff; Oct 10, 2007 at 09:31. Reason: clarification

  10. #10
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I never really used to understand interfaces either, but I have been doing some investigating (mainly talking to a friend about it!) and I now 'get them'. However the impression I got was that it is far more useful for a statically typed language like Java. That way, you can write a method that takes several kinds of objects (you have to define the type of the parameter in Java), even though you want to do the same thing with them, rather than overloading the function.

    For example, instead of:

    Code:
    method writeAsXML(Class1 input) {
      [...]
    }
    
    method writeAsXML(Class2 input) {
      [...]
    }
    
    [...]
    
    method writeAsXML(Classn input) {
       [...]
    }
    you could make Class1, Class2, ..., Classn all implement the same interface, say interfaceWriteableAsXML or something. Then, you can just do:

    Code:
    method writeAsXML (interfaceWriteableAsXML input) {
      [...]
    }
    ...and you would be safe in the knowledge that anything that implements the interfaceWriteableAsXML interface would have the same method names, so the writeAsXML function can just use those without worrying which of the classes it is that it is working on.

    I guess with a dynamically typed language like php though, it is more useful for when you have this functionality, and just want to enforce those functions to be there, kind of a way of error checking.

  11. #11
    Resident Code Monkey Chris Corbyn's Avatar
    Join Date
    Nov 2005
    Location
    Melbourne, Australia
    Posts
    713
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It can have a similar value in PHP too. PHP5 does type-hinting if you really want to use it

    PHP Code:
    public function something(YourInterface $obj) {
      
    //


  12. #12
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Yes, but it's optional in php, so it can be done in other ways (checking the input inside the function instead)

  13. #13
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by d11wtq View Post
    It can have a similar value in PHP too. PHP5 does type-hinting if you really want to use it
    Note that type-hinting is completely useless unless you use interfaces. Which makes it a circular dependency we ca easily live without. Duck typing works just as well.

  14. #14
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Duck typing?

  15. #15
    SitePoint Addict been's Avatar
    Join Date
    May 2002
    Location
    Gent, Belgium
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Per
    Everything
    works on a PowerPoint slide

  16. #16
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Ah, OK.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •