Tom McFarlin

Software Engineering in WordPress, PHP, and Backend Development

Page 5 of 424

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.

You Rarely Get Greenfield Projects (Or Do You?)

TL;DR: I’ve found this to be true in my career. In my experience, whether or not you get a greenfield project depends on your company or the nature of your team.

If courses teach you’ll be building more greenfield projects than not, I’d be hesitant to consider it a well-rounded education in software development.


Greenfield Projects Defined

For the purposes of this article, I’m using the definition of greenfield project from Wikipedia:

In many disciplines, a greenfield project is one that lacks constraints imposed by prior work. The analogy is to that of construction on greenfield land where there is no need to work within the constraints of existing buildings or infrastructure.

By definition alone, it seems near impossible to think about starting a true greenfield project. I mean, if you’re building something from scratch you have the ability to pick every set of technology and standards the team will used to build the project.

But most projects start with some type of foundation these days. With some extreme exceptions, most things are going to start at the operating system level or will use a platform like the web and likely some type of framework that sits on top of it.

And to that end, there are already certain things in place that constrain what we can use.

The Greenfield Litmus Test

If anything, I’d say a greenfield projects depends on what you consider truly starting a project from scratch.

  • Absolute purists might claim that a true greenfield project is nothing but bare metal. No operating systems, no available programming languages, etc. Everything starts here and moves up.
  • Others may draw the line at an existing operating system, existing platform, existing framework, or something like that.

When it comes to greenfield projects, I’m of the mindset that once you know what platform on which you’re building, then you determine if a project is greenfield or not.

Perhaps this is a litmus test:

  • If you’re building software that’s going to operate on or within the context of a pre-existing product, then it’s not a greenfield project.
  • If you’re building something completely new to bring to market, then it’s a greenfield project.

It’s easy to start splitting hairs so I’m not going to keep going but this is the filter through which it may be helpful to think of such projects.

Very Few Greenfield Projects

In my career, nearly everything I’ve worked on has either been a feature for a larger project (and yes, some features can be so big they take entire teams – especially at the enterprise level) or has been maintenance on a pre-existing project.

There are a few years were I worked with a very small team and we were creating several products from scratch. And the reason we were able to do that was because we had started a business of our own and were building and selling the products.

But even after those products had become more established, then we swapped into the phase of maintaining and improving the projects. So if a greenfield project comes your way, it doesn’t always stay that way.

As for now, there’s a lot of work I do that’s either related to internal tooling or based in research and development. There are times where a project may be seem like it’d be greenfield but the requirements usually dictate what’s necessary to start the project. So even then, there are constraints in place.

Do Colleges Teach You Often Get Greenfield Projects?

I don’t know what most colleges, universities, or other courses teach. This statement piqued my curiosity because I think that a lot of projects that teach software development concepts are initially done so in a vacuum. But after a certain point, you’re working with something that already exists – even if it’s small.

Though just about everything I’ve worked on out of school has been on a pre-existing project, there were also plenty of projects I had in school that were focused on adding things to projects that already existed.

Sure, some of the projects were in place so we had to learn how to work with existing codebases, but others – especially during internships – were all about maintaining existing software.

Ultimately, you’re likely to have a mixed experience but I’d venture to say the majority of projects are not greenfield.

If universities or other forms of education aren’t providing you with opportunities to learn how to both build a project from scratch and to maintain existing projects, then I’d be hesitant to consider it a well-rounded education in software development.

Colleges Don’t Teach Useful Software Development (Do They?)

With regard to what I shared in the previous post – What Do You Expect From Being a Software Developer? – the author provided 10 things I enjoyed and thought it’d be a good exercise to look at each point through my own experience.

At the very least, perhaps these things will be something to keep in mind if you’re looking to enter the industry or even for who have been working in the industry. At most, that article is something that provides a solid perspective from one person’s experience (which likely echo many others, too).

This lead me to think about my experience both in college and in my career in software development and how it relates to the ten points mentioned in the last post. It’s easy to say colleges don’t teach useful software development, but how true is that? Again, I’m not arguing the original post. But perhaps my perspective is a different.

I’m not going to give a deep dive into my entire history doing this (who would want to read that, anyway? :) but why not share my on the 10 points mentioned?


Distinguishing Between Computer Science and Software Development

I think of computer science and software development as two different things.

This is an important distinction because if you’re talking to someone who works in the field of computer science, they may or may not be in the field of software development; however, if you talk to someone in the field of software development then it’s likely they’ll be doing exactly what the title implies.

And as the field has grown in the last 10-15 years, entire degree programs or certification programs specifically for software development have emerged (as opposed to those just for computer science). That said, there are also degrees and certifications that have a foundation in computer science with a focus in software engineering, software development, web development, and so on.

All of this is worth mentioning because when we start talking about the case of if college will prepare you for a career in software development, I think it’s important to be nuanced enough to map what the college program was teaching versus what you’re expecting from the job market.

Further, it’s also worth stating that it’s not required or necessary to go to college to get a job in this job market. This was the path I chose; others have their own.

“College Will Not Prepare You for the Job”

This is where I think it’s important to distinguish between computer science and software development. When I was in school, I majored in computer science with a focus in software engineering.

If I had to summarize it, I took a lot of classes that were focused on computer science – that is, a lot of math – and then I had a lot of courses on software engineering – that is, how to analyze, design, build, and/or maintain software. For experience, I worked as a teaching assistant and participated in a few internships.

So there’s my context for the experience I’ve had thus far.

In the original article, Mensur writes:

The college will prepare you for some basics, but what most of the colleges teach is so far away from day-to-day jobs. Most of the professors who teach at universities are not good software engineers.

Only a small percentage of them even worked as software engineers. Also, the university curriculums are heavily outdated. They trot years behind the software development market needs.

college will not prepare you for the job

There are three main points in this passage I found most relevant to what I’ve done over the last 16 years (including what I’m doing now).

1. Most Professors Are Not Good Software Engineers

I can definitively say in my experience, you could tell who were the academics and who were the practitioners.

This isn’t to say either is better than the other. If, however, you’re going into the job market then those who have been there have something to offer than those who have been in academia. Conversely, if you’re looking to continue on the track of research and education, then those who have worked in the job market may not be the ones who are your best resource.

Even then, you have to know if the professor is working at the university for research or they are practicing software development by building out something that’s yet to be made publicly available. Some institutions do that and, as such, it’s not as easy to cleanly divide the two.

Generic class room all too similar. Photo Credit.

First, I can unequivocally say the professors who had the greatest impact on my career and my interest in software as a career were those who had spent time outside of an academic setting and worked in the industry (in fact, I still remember their names and many of the projects we did for those classes because they were designing from real world scenarios). A lot of practical skills were taught.

Secondly, I’m not saying those who had not worked in the industry weren’t good professors. Their methods of teaching and the projects they assigned felt far more academic in nature. A lot of theory was taught.

I know: Giving two examples relevant to my own experience doesn’t make or a solid case in one direction or the other. The goal is just to add another perspective to another published article.

The point is simply this:

  • The majority of the professors who prepared us for working in the industry were those who had already been there.
  • Those who had not worked in the industry were teaching foundational concepts – they were teaching us how to think.

And I’ll have more to say about that later.

2. University Curriculum Is Heavily Outdated

This point isn’t going to be very long because I can’t speak to the state of university curriculum. Generally, it’s a strong maybe from me. I’m sure it depends on the university or the program in which you’re enrolled.

At the time, I didn’t feel like much of the content I was learning was out of date. But it’s hard to know when you’re in school, right? What do you have to judge it against?

But looking back, there’s only one course that I took that felt out of date for me and it didn’t so much have to do with the content but it had to do with the language we were using: Smalltalk.

There’s a caveat here, though: Part of the reason we were tasked with using Smalltalk was because it was also to help inculcate the foundations of object-oriented programming where everything is an object that receives messages (versus classes and functions that are invoked on an instance of the class).

So even that served its purpose because it told us how to conceptually adapt to a weird requirement.

And for those who are wondering, there were a lot of languages used in school at the time (Java, C, Python, Smalltalk, JavaScript, SQL, and so on). But to say this is heavily outdated isn’t as true as it might be for others.

  • Was Smalltalk outdated? Yes. But I recognize the concepts taught in that class along with designing or improving object-oriented based systems were the most useful.
  • What about working with a team to scope, design, build, and test a photo sharing application? This was more applicable to what I was going to be doing day-to-day.

Now, I’ve probably forgotten certain things we were taught that are no longer needed – as is apt to happen – but one thing I distinctly remember learning that I only used in my first job out of school were UML diagrams.

I get the point of them, I understand what they are supposed to convey, but rarely do teams have the time to do this when tasked with a project. Further, it’s harder to diagram part of a project when a much larger system already exists (especially if even part of it is a legacy system).

3. Learn How to Learn

As I mentioned in the first point, the biggest advantage that I came away with when graduating with my degree was that I had learned how to learn.

No, I didn’t know all the languages but I didn’t need to know them. No, I didn’t know all the various tools, systems, languages, platforms, and so on, but I knew how to learn and adapt. And that one skill alone has likely been the one that’s paid the most dividends.

So if you’re in a program – be it something from freeCodeCamp, a course in high school, at a local college, a university program, or anything in between – it’s important to learn how to pick up something new and integrate it into your workflow.

For example, when you understand how something, say dependency injection, works in one language, it’s more or less matter of semantics when using it in another language. And that’s because the act of being able to do a thing transcends the tools used to do the thing.

Anyway, figuring out how to learn is key and we all have different ways of doing it so it’s important to find what works best for you. If that means going to office hours, doing independent reading, watching more content on YouTube, or meeting with the professor or a group of other students, or hanging out with like minded people at a conference, then do it. Whatever opportunities available that are tailored to sharpen your ability to learn, take advantage of them.

Ultimately, learning the why behind something helps you start formulating your own ways of how to learn something new. And when you get a good hold on that, picking up new technologies or applying something from a previous project or a previous job into a solving a new problem becomes easier.


Nothing I’ve shared here is a rebuttal to the previous article nor is it meant to even be argumentative. If anything, this is additional content. It’s an extension to an article someone else has already written.

And if anything else, this is a good exercise in writing something other than how to achieve something programmatically.

« Older posts Newer posts »

© 2024 Tom McFarlin

Theme by Anders NorenUp ↑