According to the Law of Demeter, can you call methods on returned objects?
E.g.
<?php
class O
{
public function m($http)
{
$response = $http->get('http://www.google.com');
return $response->getBody(); // violation?
}
}
?>
$http->get() returns an object. Does this count as an object created/instantiated within M? If you can not call methods on it (according to LoD), how would you handle this situation?
This is not a violation of the Law of Demeter, given:
More formally, the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:
- O itself
- M's parameters
- any objects created/instantiated within M
- O's direct component objects
- a global variable, accessible by O, in the scope of M
Since $response is an object that is created within M, you can invoke a method upon that object without violation. However, it would be a violation to access properties beyond getBody()
:
$length = $response->getBody()->length;
Sometimes you can say that the law can be simplified by saying it's the "one dot" rule, meaning that you can access one property or method deep.