Tom McFarlin

Software Engineering in WordPress, PHP, and Backend Development

Page 4 of 423

Thanksgiving 2023

For nearly every year I’ve written, I’ve made sure to publish a post on the end-of-the-year holidays here in the United States.

Happy Thanksgiving!
This is the earliest Thanksgiving photo I have in my library.

It’s neat to see what I wrote on this day 10 years ago in comparison to now:

For those of you who are in the United States and are celebrating Thanksgiving, I hope you guys have an awesome day hanging out with your family, friends, eating, sleeping, and generally enjoying the day off.

A lot has changed both personally and professionally since then (though I’m still working in the same industry and enjoying it as much as I always have), but the message is consistent: If you’re in the US, I hope you enjoy the time off; if you’re elsewhere, I hope you enjoy whatever you’re doing today, too.

How To Mitigate Side Effects in WordPress Development

In software development, the concept of a side effect is generally understood to be something like this:

In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, which is to say if it has any observable effect other than its primary effect of returning a value to the invoker of the operation.

Side effect, Wikipedia

The Software Engineering Stack Exchange has a great answer. You can read it in its entirety, but I really like how succinct the person puts it:

It’s really very simple. Side effect = changing something somewhere.

There are a handful of ways developers try to mitigate side effects such as automated testing or quality assurance, but when a piece of software is large enough such that each part that composes the system is like a small system unto itself, it’s not difficult to imagine how introducing new code could inadvertently change the state of the program.

This is why any given project at scale is impressive to see work as smoothly as it does. (Sure, projects like large scale web applications, operating systems, are one thing but thinking about medical software, automotive software, the software that runs on airplanes, applications built at places such as NASA, and so on are all the more amazing.)


Bringing this down to the level of stuff I write about and that I work on during my day-to-day – specifically WordPress – side effects are something we’re likely all too familiar with experiencing.

If nothing else, think about the last time you activated a plugin and it immediately conflicted with another plugin or a feature of theme.

  • It could have thrown up a notice,
  • It might have displayed an error message,
  • Perhaps it completely broke the way some part of the way the core application functions,
  • Or it just threw up a PHP error message that wasn’t even clear on what was going on.

To make matters even more fun, the only way to resolve the issue is the disable the plugin via WP CLI or, even more drastic, deleting the plugin.

This is an obvious example of a side effect in WordPress. They can happen for any number reasons, too. Sometimes it’s a matter of running a different version of PHP, it could be a matter of a team not keeping their code contained in its own namespace, or perhaps it’s a matter of not doing enough testing.

Regardless of the case, it’s something many of us have experienced and it’s likely a problem many of us have caused during our careers.

Initially, when I started thinking about side effects in WordPress development, I was working on a plugin that needed to fire when certain events happen during the user management lifecycle.

From there, I started thinking about edge cases and then I started thinking about the overall economy around WordPress and the interoperability and compatibility challenges that come with writing software that runs on top of a piece of open source software that powers so much of the web.

It’s impressive.

Then I was left at a fork of what I wanted to discuss:

  1. Should I talk about the initial problem that kicked off this entire post (that is, making sure I handled all cases of user management)?
  2. Or should I offer general commentary on edge cases and how it relates to work in building WordPress or WordPress adjacent projects?

If you’ve read this far, it’s obvious that I’ve spent more time on the latter than the former. So I’ll save the former for another day.

Since I’ve discussed this at length already, these are a few things – in no specific order – I recommend doing the following things to prevent side effects and conflicts when working on WordPress-specific code:

  • Even if you’re not using object-oriented programming, use namespaces to keep all of your functions contained within their own context.
  • Know the environment(s) in which you’re code is going to run and write for the lowest supported version.
  • When writing a custom function that will fire on a specific hook, take the time to understand the priority and number of arguments the function will expect and write your code defensively (that is, ask “how would I write this code so someone else’s won’t interfere with what I’m trying to do?”)
  • Don’t be afraid of writing unit tests not only to ensure your code is doing what it’s supposed to do but also that it’s not doing anything it shouldn’t be doing.
  • Before writing anything to any type of storage, make sure that the keys you’re using are not already in use and/or make sure to uniquely prefix the keys you’re going to use.
  • Don’t add frontend assets to any page that doesn’t need them.

I don’t know if it’s possible to put together and exhaustive list. But in my experience, these are the things that I’ve found to be helpful especially as it relates to working on backend development.

Asynchronous Methods and Headers: Just Working Isn’t Good Enough

When sending asynchronous requests to a WordPress back-end, which may be a REST API or an Ajax callback, it’s helpful to know what headers to specify when sending said data.

Since I recently shared another post about idempotency in REST API design and since asynchronous calls are more common than they have been in the past, I thought it useful to share when to use what type of headers when making said requests.

If you’re working with WordPress in some capacity – be it a headless state or working on processing Ajax calls – then it’s useful indicate how your data is being sent and in what format the data is being sent. Ultimately, your asynchronous methods and headers need to do more than just work.

That is, it’s not enough for it to simply be sent and received. Instead, the data should be sent in a format congruent with what the backend service expects. If anything, future you will thank you. To make it even more relevant, this is an opportunity to keep our code as clean as possible.


Asynchronous Methods and Headers

When creating an Ajax request in WordPress using modern, vanilla JavaScript the request will likely look something like this:

fetch(tmAcmePlugin.ajaxurl, {
    method: 'POST',
    body: data,
    credentials: 'same-origin',
    headers: new Headers({
        'Content-Type': 'application/json',
    }),
})

Notice here I’m specifying the headers as part of the request which isn’t something we’ve historically done. In this example, I’m using application/json.

It’s also common to send form data across the wire, too. And if you do that, then your request will look something like this:

fetch(tmAcmePlugin.ajaxurl, {
    method: 'POST',
    body: data,
    credentials: 'same-origin',
    headers: new Headers({
        'Content-Type': 'application/x-www-form-urlencoded',
    }),
})

Obviously, know which type of header to send and when is important. As obvious as it seems, these are the guidelines I recommend when working in the context of WordPress-centric applications.

  • Use application/json whenever you’re sending a payload that’s structured as JSON. Whenever you’re receiving the data on the server, you’ll need to use json_decode or your language’s equivalent to parse the data.
  • Use application/x-www-form-urlencoded whenever you’re sending a payload that comes from data being sent from a form element or in a string of key/value pairs such as key_one=value_one&key_two=value_two. Typically, this will be received in a POST request.

Again, however you specify the method and the header, the data will still be sent but how you manage it on the server may not match up to what’s expected.


If someone else – either someone with whom you work or just future you – reads the client-side code and the server-side code and what’s sent doesn’t match, it’s going to create an entire set of circumstances of detangling what’s been done and something that’s completely unavoidable.

Block Notes: Generate a Reference to a Block

I’m working on a block that, like many, isn’t limited to a single instance in the editor (and thus not the frontend); however, because there are certain features of the block I want to manipulate when the page loads, I want generate a reference to said block.

For example, the structure of the markup in the edit function looks something like this:

<div className="wp-acme-block">
  <div className="wp-acme-block-editor">
  </div>
  <div className="wp-acme-block-preview">
  </div>
</div>

The functionality will allow the user to toggle the visibility of the editor container and the preview container. And to manage this functionality, I want to access the parent element of each one. Specifically, the one with the class wp-acme-block.


And this is easy to do with a couple of features of React:

  • useRef is a hook that allows for direct interaction with the DOM. It returns a ref object that maintains a property called current. This enables us to maintain a reference to a specific element.
  • useEffect is a hook that handles side effects in functional components. It allows us to do a lot of things (like fetching data) but also allows us to manually work with the DOM.

Given those two hooks, I can place a ref attribute on the primary container that I can then use elsewhere in the code.

First, in the header of the file add the following:

import { useRef, useEffect } from 'react';

Then at the top of the edit function, I have the following code:

edit: ({ attributes, setAttributes }) => {
    const blockRef = useRef(null);
    // ...
};

Then, in the edit function where I have the markup that I’ve shown above, I’ll add the ref attribute:

<div className="wp-acme-block" ref={blockRef}>
  <div className="wp-acme-block-editor">
  </div>
  <div className="wp-acme-block-preview">
  </div>
</div>

And finally, I can use this reference in the edit function before it calls return so I can refer to the element in other functions.

useEffect(() => {
  acmePreviewFunction(blockRef.current);
}, []);

So the full, relevant code looks like this:

import { useRef, useEffect } from 'react';

// ...

registerBlockType('acme/example-block', {
  // ...

  attributes: {
    // ...
  },
  edit: ({ attributes, setAttributes }) => {
    const blockRef = useRef(null);

    // ...

    useEffect(() => {
      acmePreviewFunction(blockRef.current);
    }, []);

    // ...

    return (
      <div className="wp-acme-block" ref={blockRef}>
        <div className="wp-acme-block-editor">
        </div>
        <div className="wp-acme-block-preview">
        </div>
      </div>
    );
  },
  // ...
});

Then passing the current property as an argument to other functions, you’ve got access to the block such that you can manipulate it with other JavaScript functions.

Further, the ref will refer only to the instance of the block so it won’t manipulate other instances of the block located in the editor (or, more specifically, the DOM).

No One Cares About Clean Code (Or Do They?)

If you’re around my age or have been in the industry since the early 2000s, you likely think of the phrase “clean code” being synonymous with the book by the same name written by Uncle Bob (or Robert Martin).

From the description of the book:

[Robert Martin] has teamed up with his colleagues from Object Mentor to distill their best agile practice of cleaning code “on the fly” into a book that will instill within you the values of software craftsman, and make you a better programmer―but only if you work at it.

Clean Code Description

There’s a long history behind what Uncle Bob was trying to do with the software craftsmanship movement (and I don’t think his ideas were bad, for whatever it’s worth). And this book, along with a few others, helped to foster large swaths of developers to begin implementing certain practices in their day-to-day work.

This book, the author, and what it espouses is not without criticism and it seemed to get stronger the longer the book has been out. But regardless of how many practices are taught in a book – or lecture or podcast or presentation – there is always at least something to take away from it.

And though there are plenty of things in Clean Code that are tough to put into practice or aren’t always feasible to do so, that doesn’t mean some of it can’t be done.

This doesn’t refute or support the statement in the original article though, does it? Specifically, said article claims: “Nobody gives a f*** about your clean code.”

Is that true?


Who Cares About Clean Code?

A Little Bit of History (or “Back in the day…”)

When I started my first job out of college, we were used a tool called BitKeeper for version control. It’s since been discontinued. Here’s the thing about BitKeeper though: It was only for committing code. There were no other associated tools like we’ve come to expect with GitHub (such as PRs, issues, project management, wikis, etc.).

This meant that all code reviews – even if we were pair programming on a project – requested code reviews via email. So before we committed any code that would go out to staging, it needed to be reviewed by a team (of approximately seven people – they were small teams :) and it had to be done via email.

The idea of doing code reviews via email seems silly now, but that’s how it was done. Regardless, the point is we were still doing code reviews.

And this is where the concept of clean code is relevant.

At some level, it was always expected that we would be writing readable code. This isn’t necessarily the same as clean code because readable code can include a function that’s dozens of lines long and does more than one thing, but it gets the work done (whatever the work may be).

If the project allowed for it, then cleaner code and strong architecture was usually expected and if basic principles weren’t put in place then it would be brought up during a code review.

And this is where it’s important to ask: Does anyone care about clean code? Often times, it’s deadlines that matter (or the amount of time it takes to deliver a working solution).

A Hierarchy of What Matters in Software

Since having a working solution is what provides value to a user then whether or not it’s built following a particular paradigm or employing a set of principles that make for cleaner more maintainable code will always take a backseat.

If there’s a hierarchy of what’s often expected out of code, it’s something like this:

  1. It solves the problem (it works),
  2. It’s bug free (in so far as it’s measurable),
  3. It can be easily patched if a bug is caught,
  4. It’s commented so fellow developers know what’s happening if they have to jump into the fray to work on it,
  5. It follows whatever coding standard the organization implements,
  6. It follows the principles of Clean Code.

There are probably a lot more but the point I’m making is that the author is right: Clean code doesn’t matter as much as delivering a working solution.

If writing clean code delays shipping a solution then the natural consequence is you’re punting value for the customer over something they aren’t even aware exists.

The user doesn’t know how the codebase looks. The user just sees what features that product is offering. So don’t get overly attached to your clean and elegant code. Focus on shipping the feature on time and bug-free.

10 hard-to-swallow truths they won’t tell you about software engineer job

With all of that said, this is not an excuse not to attempt to write clean code, refactor when possible, or provide well-architected solutions.

Then How Can We Integrate Clean Code?

Whenever code is submitted for a code review, it’s likely that you’ll get feedback that is something like:

  • Maybe change [this particular line] to be a bit more readable such as removing the nested ternary operator,
  • Add a clause [to this function] so you’re checking to make sure something is readable or writeable before working with it,
  • Consider adding a guard clause at the top of the function,
  • If time allows, maybe create a base class and then subclass it so we don’t have some much duplicate functionality,
  • …and so on.

There are a lot of common suggestions here – so common that these are the ones that are at the top of my mind from code reviews I’ve received (and given). But did you catch the point about creating a base class? This is one of those pieces of feedback that appeals to DRY and though it’s something that would make the architecture more maintainable, it will also delay development more than the rest.

At this point, it’s likely going to be hard to implement that unless there’s enough time in the project. The other pieces of feedback will take priority.

When it comes to employing clean code in my day-to-day, I’ve found it most effective to start adding little things in as I have the chance. It’s a lot like compound interest – over time, the value adds up.

And then when you’re used to employing the small things all along, employing more strategic decisions gets easier because you’re already training your mind to think in terms of these strategies. After a long enough time of moving in this direction, you should be able to integrate writing clean code into your workflow all the while meeting the necessary deadlines.

This doesn’t mean you’re going to be employing every principle. That’s tough. But if you can start small and make those contributions over time all the while gradually training your thinking to fall in line with the principles of clean code, then it becomes the primary way in which you’ll write code.

No, you won’t always be able to do it. No, people generally won’t care about it: they’ll know what you’ve done when they see it but don’t expect praise for it. And though you may get some feedback on how to improve the code, there likely won’t be time to do so and you’ll have to earmark the suggestion and employ it in another project.


For many, it’s more popular to talk about clean code than it is to employ it. It’s more fun to talk about code than it is to write it. And it’s more fun to ship code than it is to refactor it.

So, yeah, most people aren’t going to care about your clean code. But that doesn’t mean you shouldn’t aspire to write it. I’m 16 years into my career and still working on employing new strategies with just about every project I write. I enjoy it even if code reviews don’t care about it.

And that’s because I know, ultimately, it’s going to make me a better engineer and it’s going to make the software more maintainable over time. Sure, it takes time to get there, but such is the case with just about anything worth doing.

« Older posts Newer posts »

© 2024 Tom McFarlin

Theme by Anders NorenUp ↑