Demeter’s Law vs Method Chaining – When to Use Which?

law-of-demetermethod-chainingPHP

Given this code from the Symfony framework:

use Symfony\Component\HttpFoundation\Request;

public function indexAction(Request $request)
{
    $request->isXmlHttpRequest(); // is it an Ajax request?

    $request->getPreferredLanguage(array('en', 'fr'));

    // retrieve GET and POST variables respectively
    $request->query->get('page');
    $request->request->get('page');

    // retrieve SERVER variables
    $request->server->get('HTTP_HOST');

    // retrieves an instance of UploadedFile identified by foo
    $request->files->get('foo');

    // retrieve a COOKIE value
    $request->cookies->get('PHPSESSID');

    // retrieve an HTTP request header, with normalized, lowercase keys
    $request->headers->get('host');
    $request->headers->get('content_type');
}

I think this way of accessing for example the GET and POST variables is nice. You call the get() method on the query object which is part of the request object. I think the concept of method chaining is short and nice. However, I know the drawbacks of this tight coupling. Here, my controller claims to much knowledge on the method of the query object. That is, when the query object changes its method, I would need to change all these scripts. These drawbacks are manifested in the law of Demeter.

So what is the question? My question is, when there is so much description of "good practice" how come that such popular frameworks as Symfony decide against some of these rules. Or do I misinterpret the law of Demeter? I get the impression that sometimes good practice considerations to a degree depend on personal preference. Am I wrong?

Best Answer

First of all, the Law of Demeter should not be perceived as set-in-stone rule. Is your request's structure prone to changes? Is there any additional behavior that could be invoked when getting your $request's properties? If you get "no" to both answers, I don't think that violating this "law" is such a bad thing.

Or do I misinterpret the law of Demeter?

Probably. To better understand it, I think you could look no further than this.