| 
| inheritance, fluent interfaces, and code completion [message #87247] | Fri, 19 December 2008 08:26  |  | 
| Eclipse User  |  |  |  |  | Hi. 
 I have an abstract base class called Article.  It has a mutator like this:
 
 /**
 * Set the Title of the Article
 *
 * @param string $title
 * @return Article
 */
 public function setTitle($title = null)
 {
 if (! is_string($title))
 throw new Exception('Invalid title');
 $this->title = $title;
 return $this;
 }
 
 I have a concrete sub class called News Article.  It has a mutator like
 this:
 
 /**
 * Sets the Role that is permitted to view this article
 *
 * @param string $role
 * @return NewsArticle
 */
 public function setRole($role = null)
 {
 if (! is_string($role))
 throw new Exception(sprintf("Invalid role: '%s'", $role));
 $this->role = $role;
 return $this;
 }
 
 This fluent interface allows me to write code like this:
 
 $article = new NewsArticle();
 $article
 ->setRole('public')
 ->setTitle('Foo Bar');
 
 PDT gives me nice code completion for this.
 
 However, code completion breaks when I use methods from the abstract class
 (even though the code works just fine):
 
 $article
 ->setTitle('Foo Bar')
 ->setRole('public');  // no code completion here
 
 I guess this is because setTitle has @return Article in the doc block.
 
 I could change it to @return Article|NewsArticle, but this feels wrong,
 since the base class shouldn't know anything about classes that derive from
 it.
 
 Is there a better way to do it?
 |  |  |  | 
|  | 
| 
| Re: inheritance, fluent interfaces, and code completion [message #87516 is a reply to message #87325] | Mon, 22 December 2008 19:20  |  | 
| Eclipse User  |  |  |  |  | Michael Spector wrote: > Is setRole() declared as abstract method in your Article class ?
 
 No.  I (will) have other classes that are derived from Article that won't
 have this functionality, so I don't want it in the base class.
 
 I think the only way I could get the code completion working would be to
 override setTitle() in NewsArticle:
 
 /**
 * Set the Title of the Article
 *
 * @param string $title
 * @return NewsArticle
 */
 public function setTitle($title = null)
 {
 parent::setTitle($title);
 }
 
 That'd get old pretty fast, though.
 
 I'm actually starting to wonder if the inheritance would work at all in a
 more strongly typed language.  I don't think Java, for example, would let
 me get away with the following:
 
 NewsArticle newsArticle = new Article();
 
 I might need to have a rethink this one.  Maybe it's fluent OR
 inheritance, but not both.
 
 Thanks for your input.
 
 G.
 |  |  |  | 
Powered by 
FUDForum. Page generated in 6.03589 seconds