Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

The DX Files: Defined constants as API arguments

Parent Feed: 

This is part two of my series, The DX Files: Improving Drupal Developer Experience.

Many Drupal APIs accept a boolean argument (TRUE or FALSE) to determine some behavior. I believe that practice should be banned in all but exceptional cases, instead using a defined constant with a descriptive name.

Here is a perfect example from Drupal core:

<?php
    $output
= node_view($node, FALSE, TRUE);
?>

Now, quick! Who can tell me what passing FALSE as the second argument and TRUE as the third argument means? Unless you are a Drupal guru, you almost certainly have no idea. Compare the previous line of code with this one:

<?php
   $output
= node_view($node, NODE_FULL_VIEW, NODE_IS_PAGE_CONTENT);
?>

Now it is much more clear what is going on. We're displaying the full view of a node and it is the page's primary content. Perhaps you do not know exactly what those constants mean ("A 'full view' as compared to what?", you might ask) but you are certainly better off than if you just see "TRUE" or "FALSE". If you later encountered

<?php
   $output
= node_view($node, NODE_TEASER_VIEW, NODE_IS_NOT_PAGE_CONTENT);
?>

everything would become pretty clear(*).

The end result of this change would be an API that is easier to learn and code that is easier to read, understand, and maintain.

* Disclaimer: I'll grant that it is far from obvious exactly what NODE_IS_PAGE_CONTENT actually causes to happen and in fact in a recent query on #drupal, several senior Drupal developers (myself included) couldn't remember, but it is still way better than "TRUE". This is an unrelated issue with node_view() that ought to be improved.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web