note 114455 added to language.oop5.final

From: Date: Sat, 22 Feb 2014 22:18:53 +0000
Subject: note 114455 added to language.oop5.final
Groups: php.notes 
Request: Send a blank email to php-notes+get-198591@lists.php.net to get a copy of this message
@someone @thomas Decorating a finalized class is not possible. The decorator that's mentioned is incomplete. There's a fundamental flaw in it. Look: <?php //copy'n'paste your FooBar, Foo definition $f = new Foo; $fd = new FooDecorator($f); var_dump($fd instanceof $f); //FALSE var_dump(is_a($fd, 'Foo')); //FALSE fooFoo($fd); //E_RECOVERABLE_ERROR here !!!; ?> What you've created is just an object that happens to have the same methods(a duck type). But if in the client code someone makes decision based on the type of your passed decorator they'll make incorrect decision - or to be more precise not the one that you, the author of the 'decorator' wants them to make. FYI that's the correct implementation based on GoF: <?php class Foo { public method doFoo() { // do something useful and return a result } } //decorator must inherit the interface(the methods, type info etc.) //of the decorated class by *extending* it. class FooDecorator extends Foo { private $foo; public function __construct(Foo $foo) { $this->foo = $foo; } public function doFoo() { $result = $this->foo->doFoo(); // ... customize result ... return $result; } } function fooFoo(Foo $f) {} $f = new Foo; $fd = new FooDecorator($f); var_dump($fd instanceof $f); //true fooFoo($fd); //no E_RECOVERABLE_ERROR here; ?> I haven't come across any legitimate use of a finalizing class/method and I personally think that 'final' is has no much use and is just a copy'n'pasted from Java into PHP. The keyword makes code difficult to test. If you have to create a test double from a finalized class because you'll need create a derived type to shadow the methods you don't care about. If one of them is finalized you've already lost. ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/language.oop5.final.php Edit -- https://master.php.net/note/edit/114455 Del: integrated -- https://master.php.net/note/delete/114455/integrated Del: useless -- https://master.php.net/note/delete/114455/useless Del: bad code -- https://master.php.net/note/delete/114455/bad+code Del: spam -- https://master.php.net/note/delete/114455/spam Del: non-english -- https://master.php.net/note/delete/114455/non-english Del: in docs -- https://master.php.net/note/delete/114455/in+docs Del: other reasons-- https://master.php.net/note/delete/114455 Reject -- https://master.php.net/note/reject/114455 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198591) next »