The DX Files: Defined constants as API arguments

Barry Jaspan's picture

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?

read more

the first FALSE means "do

the first FALSE means "do not show node teaser as node content when viewing a node, display node body only"
the last TRUE means "the node will be displayed by itself as a page"

tell me if i made some mistakes
:)

cora

Using an IDE I can see the

Using an IDE I can see the parameters after writing the function name (CTRL+space or something), also I can see the descriptions of the parameters...

I don't think this should be banned at all....

There are others DX issues

There are others DX issues more important than this one, this is very, very minor if you have the functions parameters documented.

I am not sure I would

I am not sure I would consider this a huge problem either really seeing as for the most part we do a decent job documenting, but I would agree that perhaps constants passed as a single argument or bitmask flags may be a little more readable

What I find even weirder is

What I find even weirder is that it makes this possible:

<?php
return node_view($node, TRUE, TRUE);
?>

Why would you want a node_view to be both a teaser and a page? If you answered, "Because you have no idea what you are doing..." you'd be correct.

That said, the way the system treats pages and teasers is completely different -- so different that I don't know weather this is appropriate:

<?php
// though it would be more flexible to let you do whatever for the $op, so you aren't limited to two types of views...
function node_view($node, $op = 'teaser') {
//...
}
print
node_view($node, "page");
?>

I could live with this however:

<?php
function node_view($node, $page = false) {
}
//Even better would be simply this:
// "view" is a full page view
$node->view();
// teaser allows you to bypass the normal theme functions for special cases
$node->teaser('some_theme_function');
?>

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <blockquote> <p> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Syndicate content