MODX Snippet Development III

In the last article, we cleaned up our snippet code to make it more readableMODX logo and to meet some standard coding practices. We’ll do some more of that in this article and fix a logic error in the code.

Notice that we’re still not even thinking about adding features to our snippet. It’s important to have nice, clean, correct code before considering new features. Otherwise, adding the features will be more difficult, and more likely to cause errors. Adding new features to a poorly designed snippet also tends to force you to redesign it again and again.

Starting Point

For reference, here is the snippet as it appeared in the last article:

[code language=”php”]
<?php
/* NewResource snippet */

/* Get the publishedon date (if any) and
convert it to a unix timestamp */
$pTime = strtotime($modx->resource->get(‘publishedon’));

/* Get the current time as a timestamp */
$currentTime = time();

/* Get the resource’s age in seconds */
$age = $currentTime – $pTime;

/* Set $interval as the number of seconds in two weeks */
$interval = 1209600;

/* See if the resource is published */
$published = $modx->resource->get(‘published’);

/* Set the return value */
$output = ‘<span class="new_resource">NEW!</span>’;

/* See if publication date is within the last two weeks */
if ($age < $interval ) {
/* Yes, it’s recent. If published, return NEW! */
if ($published) {
return $output;
}
} else {
/* Not recent, return an empty string */
return ”;
}
[/code]

Logic Trouble

At this point, it’s important to stop and think about whether the snippet will always do exactly what it’s supposed to. Part of that is thinking about all the situations the snippet will encounter. In this case the snippet will be faced with both old and new documents and with published and unpublished documents. That makes four possible conditions: old published, old unpublished, new published, and new unpublished. Take a look at the snippet above and see if you can spot the problem.

Did you see it? What does the snippet return if a document is recent but unpublished? If you look closely at the code, you’ll see that the snippet has no opinion on the matter. It doesn’t return anything in that case. All snippets should have a return value (unless they *never* return anything), so it’s a potential problem if one just ends without returning anything at all. We’ll fix that in a bit, but first some thoughts about efficiency.

Code Efficiency

It’s a little early to to be thinking about this, and we’re certainly not going to do any optimizations at this point that will make the code less readable, but it’s good to keep this in mind since the logic error is forcing us to do a little redesign.

The principle involved here is simple: Never have your snippet execute code it doesn’t have to execute. As currently designed, our snippet is doing pointless calculations to find the age of unpublished resources. In this case, it’s not really important, since no typical user is every going to have to wait while those calculations happen (since they’ll never see an unpublished resource). The issue is academic here, but in many snippets, the difference is critical. For practice, then, while we’re redesigning this snippet to handle all cases, let’s get rid of that inefficiency.

One Exit Point

While we’re at it, we’ll make another design improvement. It’s not always practical, but a good goal in snippet design is to give the snippet a single return statement at the bottom. I will occasionally violate this for the sake of readability, putting a return statement at the very top that skips the whole body of the code if some condition doesn’t apply. In plugins that handle resources, for example, I’ll sometimes simply return at the top if the resource is or isn’t new.

I also sometimes violate the “One Exit Point” principle when I have a very complex, poorly designed section of code that I don’t have time to redesign and test from scratch. In those cases, I’m always sorry that I didn’t spend more time designing the code properly to begin with.

The best way to remind yourself to do this right is to start *every* snippet with this code:

[code language=”php”]
<?php
/* SnippetName snippet */

$output = ”;

/* Code goes here */

return $output;
[/code]

Improved Code

[code language=”php”]
/* NewResource snippet */

/* Default return value */
$output = ”;

/* Return value for new resources that are published */
$newOutput = ‘<span class="new_resource">NEW!</span>’;

/* Set $interval as the number of seconds in two weeks */
$interval = 1209600;

/* See if the resource is published */
$published = $modx->resource->get(‘published’);

/* For published documents, see if publication date is
within the last two weeks */
if ($published) {
/* Get the current time as a timestamp */
$currentTime = time();

/* Get the publishedon date (if any) and
convert it to a unix timestamp */
$ptime = strtotime($modx->resource->get(‘publishedon’));

/* Get the resource’s age in seconds */
$age = $currentTime – $ptime;

if ($age < $interval) {
/* Yes, it’s recent – return NEW! */
$output = $newOutput;
}
}

return $output;
[/code]

This is much better. We’ve got a single exit point at the end which will always return a value. Since we’ve set it to an empty string at the top of the snippet, we don’t have to do anything with the $output variable in the snippet unless we want to change that. This eliminates the else statement. We’ve also wrapped the calculations in if($published) {} so they won’t be performed unless we really need them.

Notice that the variables a user might want to modify are still at the top. The ones we moved are only used for the calculations and would never be set by the user. We had to create a new variable $newOutput, which will be set unnecessarily for unpublished resources, but putting it here keeps the user from having to search for it in the code below, and setting it will only take a few milliseconds (possibly microseconds), and as we’ll see in the next article, we’re going to want that variable when we start adding features.

The code still has design problem, which we’ll deal with in the next article. It will work perfectly, though, and the design problem could be considered excusable in a quick utility snippet.


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or
better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than <a
href=”http://bit.ly/YgFGHl”>Arvixe Web Hosting!

Tags: , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray is the author of MODX: The Official Guide and over 30 MODX add-on components. He hosts Bob's Guides, a source of valuable information for MODX users, and has been very active in the MODX Forums with over 19,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *