When a method is returning the result of a call to another method, what is the sensible way to document the return type?
class A
{
/**
* @return [How do I know here what bar will return?]
*/
public function foo()
{
$b = new B();
return $b->bar();
}
}
class B
{
/**
* @return string
*/
public function bar()
{
return 'baz';
}
}
How do I document A::foo()
return type, when it is not certain what B::baz()
will return? In the future, B::baz()
may change, in which case the return type of A::foo()
unknowingly changes.
Is this a code smell? Can the wider code be designed so that the return type of A::foo()
is predictable even if B::baz()
changes?
If you fear that the bar()
return type could change without regard to what your foo()
expects, then I'd say it is indeed a code smell. There's apparently no contract between the two, so there's no trust from A
to B
.
More practically, bar()
is documented to return string
, so by having foo()
coded to return bar()
's actual return, then foo()
should be documented to also return string
. There won't be an automatic way for the doc generator / IDE to keep up with this for you, if that's what you're after.
The other doc-only option would be to mark foo()
's return as mixed
, thereby telling the reader "I make no guarantees on what I return, because I'm only giving you what bar()
gave me, and I don't know ahead of time what that will be".