5

One can accomplish same thing using different tools. So have I in examples below.

One shows use of interface/polymorphism (source: nettuts - I think). Another straightforward class interactions (mine) - which shows some polymorphism as well (via call_tool()).

Would you tell me, which would you consider to be a better way.

Which is safer, more stable, tamper resistant, future proof (afa code development is concerned).

Please scrutinise scope/visibility used in both.

Your general recommendations, as which is best coding practice.

INTERFACE:

class poly_base_Article {

    public $title;
    public $author;
    public $date;
    public $category;

    public function __construct($title, $author, $date, $category = 0, $type = 'json') {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;

        $this->type = $type;
    }

    public function call_tool() {
        $class = 'poly_writer_' . $this->type . 'Writer';
        if (class_exists($class)) {
            return new $class;
        } else {
            throw new Exception("unsupported format: " . $this->type);
        }
    }

    public function write(poly_writer_Writer $writer) {
        return $writer->write($this);
    }

}

interface poly_writer_Writer {

    public function write(poly_base_Article $obj);
}

class poly_writer_xmlWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {
        $ret = '';
        $ret .= '' . $obj->title . '';
        $ret .= '' . $obj->author . '';
        $ret .= '' . $obj->date . '';
        $ret .= '' . $obj->category . '';
        $ret .= '';
        return $ret;
    }

}

class poly_writer_jsonWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {
        $array = array('article' => $obj);
        return json_encode($array);
    }

}

$article = new poly_base_Article('Polymorphism', 'Steve', time(), 0, $_GET['format']);
echo $article->write($article->call_tool());

NON-INTERFACE

class npoly_base_Article {

    public $title;
    public $author;
    public $date;
    public $category;

    public function __construct($title, $author, $date, $category = 0, $type = 'json') {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;
        $this->type = $type; //encoding type - default:json
    }

    public function call_tool() {
        //call tool function if exist
        $class = 'npoly_writer_' . $this->type . 'Writer';
        if (class_exists($class)) {
            $cls = new $class;
            return $cls->write($this);
        } else {
            throw new Exception("unsupported format: " . $this->type);
        }
    }

}

class npoly_writer_jsonWriter {

    public function write(npoly_base_Article $obj) {
        $array = array('article' => $obj);
        return json_encode($array);
    }

}

class npoly_writer_xmlWriter {

    public function write(poly_base_Article $obj) {
        $ret = '';
        $ret .= '' . $obj->title . '';
        $ret .= '' . $obj->author . '';
        $ret .= '' . $obj->date . '';
        $ret .= '' . $obj->category . '';
        $ret .= '';
        return $ret;
    }

}

$article = new npoly_base_Article('nPolymorphism', 'Steve', time(), 0, $_GET['format']);
echo$article->call_tool();

MikeSW code (if I get it right)

 class poly_base_Article {

    private $title;
    private $author;
    private $date;
    private $category;

    public function __construct($title, $author, $date, $category = 0) {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;
    }

    public function setTitle($title) {
        return $this->title = $title;
    }

    public function getTitle() {
        return $this->title;
    }

    public function getAuthor() {
        return $this->author;
    }

    public function getDate() {
        return $this->date;
    }

    public function getCategory() {
        return $this->category;
    }


}

interface poly_writer_Writer {

    public function write(poly_base_Article $obj);
}

class poly_writer_xmlWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {

        $ret = '';
        $ret .= '' . $obj->getTitle() . '';
        $ret .= '' . $obj->getAuthor() . '';
        $ret .= '' . $obj->getDate() . '';
        $ret .= '' . $obj->getCategory() . '';
        $ret .= '';
        return $ret;
    }

}

class poly_writer_jsonWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {
        //array replacement
        //$obj_array = array('title' => $obj->getTitle(), 'author' => $obj->getAuthor(), 'date' => $obj->getDate(), 'category' => $obj->getCategory());
        //$array = array('article' => $obj_array);

        $array = array('article' => $obj); //$obj arrives empty
        return json_encode($array);
    }

}

class WriterFactory {

    public static function GetWriter($type='json') {
        switch ($type) {
            case 'json':
            case 'xml': $class = 'poly_writer_' . $type . 'Writer';
                return new $class;
                break;
            default: throw new Exception("unsupported format: " . $type);
        }
    }

}

$article = new poly_base_Article('nPolymorphism', 'Steve', time(), 0);
$writer=WriterFactory::GetWriter($_GET['format']);

echo $writer->write($article);

2 Answers 2

2

Ahem, your approaches have some flaws no matter what version. First thing, the poly_base_Article exposes the fields which breaks encapsulation and kinda defeats the purpose of using OOP in the first place.

Next, you have a fine injection there via the $_GET parameter. THe proper way to do the class should be like that

 class poly_base_Article {

private $title;
private $author;
private $date;
private $category;

public function __construct($title, $author, $date, $category = 0) {
    $this->title = $title;
    $this->author = $author;
    $this->date = $date;
    $this->category = $category;

}

 public function getTitle() { return $this->title;}
 //...other getters defined here...

   public function AsArray()
     { 
          return (array) $this;
     }

//this could be removed
public function write(poly_writer_Writer $writer) {
    return $writer->write($this);
}
}

The write method doesn't seem to be required though, you just tell the writer to write the object directly.

The *call_tool* method should belong to a service or as a factory method to create an instance of poly_writer_Writer (btw, you should change the naming of the classes and interface to something more natural), something like this

class WriterFactory
 {
     public static function GetWriter($type='json')
      {
         switch($type)
         {
            case 'json'
            case 'xml': $class= 'poly_writer_' . $type . 'Writer'; 
             return new $class;
              break;
             default: throw new Exception("unsupported format: " . $type);
           }
        }
 }


  $article = new poly_base_Article('nPolymorphism', 'Steve', time(), 0);
   $writer=WriterFactory::GetWriter(, $_GET['format']);
 echo $writer->write($article);

Which is safer, more stable, tamper resistant, future proof (afa code development is concerned).

That depends only on the developer skill and discipline. In this particualr case, the code I've written is the safer, tamper resistant and future proof :P

Update Indeed, I forgot to put getters in the poly_base_Article, I've added them now. Since you're doing serialization, the article shouldn't know about it, as it's not his responsability (it's part of the infrastructure layer) so the write method is not required at all, but that's a specific case here (in the everything depends on the context).

The WriterFactory is basically the factory pattern which creates an instance of the writer and returns an abstraction - that's the polymorphism where the interface is useful. This approach makes it very easy to add new implementations of the interface and also to guard against code injection.The switch is to check that only the valid values of $type are permitted. You might validate the $type in other places but this is the only place which should handle everything related to creating writers. Even if you want to validate outside it you just create a static method in the WriterFactory which will return true/false and use than.

About interfaces being a fad... using interfaces is how OOP should be done. It's a best practice to program against an abstraction and the interfaces are the 'best' abstraction. To put it bluntly: if interfaces are a fad, then OOP is a fad.

About your second example, well the first too, the method which creates the writer should not be there in the first place as it couples the creation of the writer to the article and those 2 have pretty much nothing in common. It's a breaking of the SRP (Single Responsability Principle).

In this particular case, once you are doing the creation factory in a separate class then you pretty much don't care about the interfaces, however that because the usage is very simplistic here and you're using PHP or a loosely type language. If you would pass the writer as a dependency then it will help to pass around the interface and not an actual implementation (like you did in the first example). It's very helpful to know what type you're passing around.

Also In a language like C#, you would have a return type and then, as an optimum usage, you would return it as the interface type (C# supports dynamic types which let's say behave a bit like in PHP so you can return dynamic and not care, but that comes with a performance penalty and if the type returned doesn't have the method invoked it will throw an exception)

Sign up to request clarification or add additional context in comments.

12 Comments

$_GET - that was really not part of q. ;), so I did not pay much attention. In live code it would be properly looked at from every angle. But you are right, I should not let it go through, even if that was out of q. scope.
if you make poly_base_Article properties private, how can e.g. poly_writer_xmlWriter access them? there is no relation between them
WriterFactory - isn't this just creating additional object without much functionality added by it?
switch in factory: isn't it just adds unnecessary update point, if you are adding additional poly_writer_[type]Writer? In both example codes, all you have to do is to write writer class.
and the last one :) isn't using interface is just a fad? a run for something new? second example seems to serve purpose just as well ... actually that was a main question here
|
1

I would begin the whole thing by recommending this video, and other videos from series.

There are two conditions which would make interfaces preferable:

  • you are working in a team
  • long term project

Use of interfaces acts like another set of documentation, when you need to expand the functionality of your codebase. Also the principle of least astonishment is used then.

In a very small & quick project there is no point in using interfaces.

1 Comment

I'm using interfaces anywhere I need to abstract something regardless of the size of complexity of the project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.