Why SitePoint Lost Against Incremental Evil

“All that is necessary for the triumph of evil is that good men do nothing.” — Edmund Burke

As a codebase ages, its Software Brittleness increases, making it more difficult and expensive to adapt to changing market conditions, add new features and fix bugs. At some point, the ROI for almost any change can be negative, leading to a product that can no longer keep up with its market changes. This is its local optimum.

Some systems may get stuck in a rut that requires enormous effort to overcome the initial slump before reaching new heights.

To achieve the global optimum (here meaning best viable product possible), the cost of implementing new features needs to come way down. This can be done by reducing the codebase’s brittleness and inversely increasing its malleability.

One way to get there is by re-writing the system from scratch. And that’s exactly what SitePoint did in 2013: they overhauled the entire website and made not an evolutionary change to their product, but a revolutionary one.

The SitePoint Redesign

Here is a before-and-after shot of SitePoint’s article design from their big announcement post:

It’s easy to see that the old design was stuck in a local optimum and getting from the “before” design to the “after” design would have required the following hurdles to be overcome:

  • Convince the Social Media team to get rid of the Like / Share / Tweet / Email buttons
  • Convince the CEO to make the logo smaller (see: Make The Logo Bigger Cream)
  • Convince the Bookstore Department to remove the “NEW SITEPOINT BOOK. Read Chapter 1 FREE!” ad
  • Convince the SEO team to remove the bright red category links

Since requesting any of these things would generally be met with furrowed brows and rejection, the designers were able to avoid the problem by starting from scratch.

The final writeup says the redesign allowed them to:

  1. Focus the user experience towards the actual article content
  2. Be stylish and sleek
  3. Implement responsive design
  4. Improve site search
  5. Improve page load time
  6. Increase discoverability
  7. Engage in a two-way conversation

These were all admirable features, and the redesign came out quite nice. It had a clear focus on the content and removed distractions. It cleaned up the colour palette and made the UI simpler. It made the pages load faster and the search deliver better results. But there’s one thing it didn’t do: it didn’t stay nice.

“For The Leaves, They Will Wither”

SitePoint has not had a major redesign since then. However, their once clean-and-performant website has devolved into a mess of ads, anti-patterns, bloat, privacy invasion and content obscuring.

Here’s what a user sees when visiting that same page today:

Wow. Take that UI in for a moment. Think of how much it really meets its original goals. Ask yourself:

  • Does this UI focus on the article content?
  • Is this stylish and sleek?
  • Does the page load the main content as fast as possible?

Upon first glance, the answer to all of these questions is no. Here’s an annotated version of what the user gets to experience now:

All the sections highlighted in red are the parts of the UI actively pulling the user’s attention away from the actual content, highlighted in green. That’s an astounding signal-to-noise ratio, and is made worse by the other dark patterns at play:

  • Instantly asking for push notifications permission
  • Obscuring the article with a darkening screen and cold-pushing the ebook (with the mandatory surrender of personal email data)
  • Having a bright-red, full-width banner at the top of the screen (that sticks there when the user scrolls down)
  • Adding a countdown timer that can flicker in the user’s peripheral vision every time the seconds counter ticks down
  • Informing the user that if they click anywhere in the page, they’ll opt-in to cross-site ad tracking
  • Having three sidebar advertisements visible above-the-fold

This user experience when taken as a whole is objectively bad. But clearly nobody set out to turn SitePoint into that mess — it devolved over time, degrading the UX not all at once, but getting slightly worse, bit-by-bit. The term for this is Incremental Evil.

How Incremental Evil Takes Hold

These dark patterns, ads and distractions tend to get added one at a time, usually under the guise of minor conversion improvements, or to coincide with other promotions.

For example, when the ebook was released, the SitePoint marketing team probably asked to add the email nag modal (or even circumvented the ownership of the product and did it themselves using some injectable digital marketing system). With no real evidence for rebuttal, the developers were forced to accept the addition. One single modal was no big deal, right?

Then later, one of the higher-ups hears that many browsers allow sites to send push notifications right onto the users’ device — a lucrative marketing vector too good to pass up. So, the developers add the push notification prompt. Sure, it’s annoying. Sure, it adds another thing standing between the user and the content they came to see, but it’s still just a minor thing, right?

Even later, the SEO team wants to try an optimisation experiment to see if users want to find related tutorials by topic. Thus, once again, the developers are asked re-implement the big list of category links that were so boldly removed in the redesign. They do it anyway because the SEO budget is very large and it’s really just one small thing, right?

Defending Against Incremental Evil

As the old saying goes, the water heats imperceptibly until the frog boils to death. In SitePoint’s case, it was the usability, simplicity and performance of the UI that was slowly eroded until site visitors were treated to an all-out assault on their attention, bandwidth and tolerance.

But why did this happen to SitePoint, and why do so many other software products experience this quality rot? I think the answer lies in the incremental nature of these changes and the lack of fundamental strategic principles.

If SitePoint’s designers and developers had a set of fundamental strategic principles, they could have been more effective user champions in the face of well-meaning but incrementally-evil changes.

I submit that a user champion need not be a person, but perhaps a written document. Such a document could define (in whatever detail) the framework and ground rules that a project or system must adhere to. With the right authority, such a document could assist in the prevention of quality rot and ensure that great products stay great.

A written artefact that underscores the fundamental guiding principles of a system, product or project can take many forms. There are several recognisable analogs throughout the history of society and business.

Constitutions

For centuries, nation states would write a Constitution; a document outlining the rights and rules by which all of its citizens must abide. The contents of these documents could be purposefully high-level and concerned with holistic governing practices, usually concerning citizenship, liberty and justice.

This mandated that legislators write laws which fell within the legal boundaries set out within the supreme authority of the higher-ruling constitution. Any single actor (such as a malevolent local governing body) who attempted to pass through legislation that would erode the rights of the citizenry would find that their laws were unconstitutional and would therefore be unenforced.

Thus, the constitution was the written artefact that functioned as a written user champion, surviving successive governments and social revolutions to protect the citizenship and keep the nation aligned with its ideals.

User Stories

In Agile software development, a user story is a tool used “to capture a description of a software feature from an end-user perspective. The user story describes the type of user, what they want and why”.

The rest of a feature’s requirements and subsequent implementation are subject to the fulfilment of the original user story’s expectations. No matter what is built, if it doesn’t meet the expectations of the user story’s hypothetical persona, the work must not pass QA.

Performance Budgets

The digital design and UX movements are slowly coming around to the idea that performant, responsive interfaces are a worthwhile UX endeavour[15]. Some even go so far to say performance is a feature. Some case studies show a financial benefit to increasing the speed of webpage load times[17].

Instituting a performance budget for a cloud product will force web designers and developers to consider the bandwidth, latency and operational performance of their product. This manifests itself in things like compressed assets, reducing download and parse times, minimising the use of font faces and ensuring the UI is never blocked by some expensive task.

All these things together ensure the user is delighted with their experience using the product, in addition to the features of the product itself.

Conclusion

There is a great case study to be found in SitePoint’s relapse of quality rot. If you notice a product, system or interface being slowly degraded by ads, dark patterns or other stepwise degradations, communicate your frustrations to the vendor. Ensure that products you or your colleagues are building may not fall victim to incremental evil, and always advocate for the customer — they’re the ones who matter the most.

For more information about what should go into a user-champion document, keep an eye out for Part 2 of this post; coming soon.

Partial To Perfect: When Is A WordPress Theme Complete?

WordPress is not just a blogging product: it’s a platform for creating websites, online stores and more. This distinction means that it’s not just the website owners who need a good user experience: somewhere along the way, actual programmers need to interact with its internals.

As Lee Cohick explains, the quality of this interaction influences the quality of the platform as a whole:

When a product transitions into being a platform, it takes on a new type of user: the third-party developer. When developers build their own products on a platform, they are in effect users of that platform. But they are a special type of user, one that behaves as an intermediary between end users and the platform product.

An end user’s experience with a platform product, such as the iPhone, includes the experience of using third-party apps. Every app is a use case that should reflect the user experience of the principal product. Platform product owners must be concerned with assisting developers in accomplishing this if end users are to have a good user experience overall. Attention to these details is called developer experience (DX), and enabling app developers to be successful through better DX will create a more successful UX for the platform product.

One equivalent of third-party apps for WordPress is themes. The Developer Experience for themes sets a low barrier of entry — which of course can result in many low-quality themes.

Clearly it takes very little to make a working WordPress theme. But how much extra effort is it to make a complete theme?

To answer this question, we’ll create one from scratch and — through multiple successive levels — see how comprehensive it gets before one would consider it a functionally complete theme.

Sam's Skateboards Logo
Skater icon by Nora Valadez from the Noun Project

To show off the capabilities of each level discussed in this post, we’ll apply the theme to an imaginary website called Sam’s Skateboards.

With each successive feature introduced, we can see how a WordPress website can be built to make use of that feature. We’ll call the theme Kickflip.

Level 1: The Minimum Required

The absolute minimum that WordPress requires to even recognise a theme is:

  • A stylesheet called style.css
  • A template file called index.php

This will add a new option in the Themes Administration Panel for selection:

The basic Kickflip theme option available for selection
The basic Kickflip theme option available for selection next to the default Twenty Sixteen theme.

At this point, the theme can be activated, but it certainly won’t do much. We should add some code in index.php:

Now, the page’s content will actually print out to the screen:

The homepage for Sam’s Skateboarding generated by WordPress with just the basic markup.
The Contact Us page generated from the same markup

With just the code in index.php we have a functional (albeit ugly) website.

  • The page’s title in the <title> tag
  • The page’s title in a <h1> at the top of the page
  • The content of the page in the body

As a valid document complete with working hyperlinks, this is basically a complete implementation of Tim Berners-Lee’s original World Wide Web dream. But to stand up as a worthwhile site on the modern web, we can do better.

Level 2: Styles, Favicons And Other Basics

The current best practice for adding style to webpages is through CSS. Since WordPress believes “options are bad”, the decision for how to include CSS on the page has already been made for us: using style.css.

Adding Styles

The official way to include the style.css file on the page is to enqueue it in a special file called The Functions File. This file does all the theme-wide heavy lifting and generally has the same capabilities as WordPress plugins do, but only executes when its theme is active.

So now we create a Functions File called functions.php and enqueue our main stylesheet from there:

Once we’ve done that, we can start styling our page by filling out the contents of style.css:

This will load the stylesheet and give our page a bit of personality!

The home page with some basic styles
The home page with some basic styles

Adding A Favicon

As of WordPress 4.3, theme authors should not write any code to display favicons or site app icons — WordPress now does it natively from the Customizer. If you have an existing theme that does this, you should migrate to using the WordPress core’s in-built functionality.

Proper Site Title

Right now the <title> for each page is simply set to display the title of the current post. This is not ideal since WordPress has many powerful title features that it can’t put to good use if the theme is dictating the page’s title. Also, many plugins may modify the title, so it’s best to let the WordPress core handle it.

Since WordPress 4.1, this is done by adding a simple one-liner into the Functions File:

Now we can safely remove the hard-coded <title> tag from index.php:

Now the page title will be handled by WordPress internally, according to whatever plugins and settings the theme’s users have enabled:

The dynamic page title generated by WordPress

Theme Metadata

If we look at our theme in the Theme Chooser, it’s obvious that there’s a bit of information missing:

sams-skateboards-com-wp-admin-themes-php-themekickflip

Clearly we want to fill this out a bit.

Theme Thumbnail

To fill that empty rectangle with a picture of our theme, we just need to place a picture called screenshot.png into the theme’s root directory. Doing that will automatically make it show up.

Theme Details

WordPress themes have several different detail fields that authors can fill out. There are many optional fields, but at a minimum you should put:

  • Theme Name
  • Author
  • License

You add these fields to the File Header of style.css. Then, WordPress will automatically parse that information and show it where necessary.

After filling out the theme details and creating a theme thumbnail, your theme should look much more complete:

A well-completed theme summary
A well-completed theme summary

Is The Theme Complete Yet?

Right now we have a functional website running a valid theme that has the following features:

  • Dynamic title
  • Valid HTML5
  • Dynamic body content
  • Fully-completed metadata

While this does give us a functional website and a valid theme that is a bit better than the barebones Level 1 theme, here’s some things that are still missing:

  • Responsive design
  • Specifically-designed page templates
  • Search page
  • 404 page
  • Widgets
  • Sidebars
  • Semantic content width registration
  • Automatic feed links
  • Custom backgrounds
  • Post thumbnails
  • Post formats
  • Editor style
  • HTML5 markup opt-in
  • Theme logo
  • Menus
  • Translations & multilanguage support

Clearly this theme is functional, but not complete. Let’s keep building!

Level 3: Responsive Design, 404 Page And Search Page

Enabling Responsive Design

At present, our theme is not very mobile-friendly. To make the page’s content look better on all devices (as well as boost SEO scores), we want to tell the browser to render the page as a proper mobile-friendly document, rather than emulate a desktop-sized browser.

To make this happen, we need to add the following line into the <head> of index.php:

And now mobile browsers will fit the content much more appropriately:

enable-responsive-mode-comparison
Left: the page as seen by default. Right: after telling the browser to display the page responsively.

Other Navigation Pages

404 Page

Eventually, some site visitor will trigger a 404 Page Not Found error on every site. If it happens on a site with a theme that does not handle this, the result is not very professional:

An unhandled 404 error.
An unhandled 404 error.

Notice there’s no indication of the error or what caused it, so the user can get frustrated and leave the site. We want our theme to be professional and complete, so we can fix this by creating a new page called 404.php. This is the file in the WordPress Template Hierarchy that will be loaded when the site needs to show a Page Not Found error.

To fill this page, base its content off what’s in our original page template, index.php but with a slightly different main section:

So now, this page will show any time that the requested post or page can’t be found:

A properly-handled 404 error

Roadblock: Duplicated Theme Code

Since the design of the index.php and 404.php are very similar, they necessarily share a lot of the same code, including everything in the <head> and <footer>.

Because it’s a good idea to follow the DRY principle, we should make use of WordPress’ built-in solution for splitting out headers and footers into their own partial template files.

Now we create a file called header.php and fill it with everything from the doctype declaration to the point where each page diverges into unique lines of code. And then we do the same for footer.php, except that gets filled with everything from the end of the divergent point to the closing </html> tag:

By using the get_header() and get_footer() hooks, we can keep all our shared header and footer code in their own separate files, and fill the page templates with only what they need specifically for that page.

Side note: there is a difference between wp_footer() and get_footer().

Search Page

The WordPress Template Hierarchy has a special page template for displaying search results, since we generally want to show a snippet of results instead of entire pages.

To create a search page, we add a new file called search.php to the theme’s directory and fill it with appropriate content. This should give us a reasonable search results page:

A well-built search page
A well-built search page

Is The Theme Complete Yet?

We’re starting to have a great theme for the purposes of showing webpages and handling related edge cases. But is this enough?

Many users will want to add in menus and widgets. In fact, WPBeginner says sidebars are an absolute must-have. Add that to the ubiquity of menus around the web and it would be hard to call a theme complete without them.

While there’s nothing technically wrong with the theme as it is, we still have to cater to user expectations for using this theme, and visitor expectations while consuming the theme-presented content.

Let’s keep building!

Level 4: WordPress-Specific Features

Dynamic Menu Areas

Any website worth its salt has at least one navigation menu. With WordPress, the theme can define menu areas that users can fill with their own customised menus.

Here we use the hook register_nav_menus() in the Functions File to create two menu areas: one in the header and one in the footer:

This gives the owners of the site the ability to use the WordPress Menu Panel to create custom dynamic menus:

WordPress now recognises two menu areas: a Header Menu and a Footer Menu
WordPress now recognises two Theme Menu Locations: a Header Menu and a Footer Menu

Header Search

While we created a proper search form earlier, there was no way to actually invoke a search short of typing your query into the URL bar.

Using the built-in get_search_form() hook, WordPress will print out a semantic, valid, working search form ready for use and styling:

sams-skateboards-com-contact-us
A properly-implemented WordPress search form.

Sidebars & Widgets

As mentioned, sidebars are a very important part of the WordPress platform and users expect to be able to customise them and fill them with widgets.

Fortunately for theme authors, this is a simple matter. Using the register_sidebar() hook, we can register a dynamic sidebar area just like we previously did for menus.

Combined with creating a new file called sidebar.php, we can add this theme feature to the site in no time:

A page showing the new sidebar with some widgets activated.
A page showing the new sidebar with some widgets activated.

Some themes have other areas where widgets can be dynamically inserted by the site owner, like the footer or even the header. Each successive widget area is defined and implemented in the same way.

Other Page Templates

According to the WordPress Template Hierarchy, our theme can — in some capacity — display all the content and media that a site owner can throw at it:

  • Search pages are shown using search.php
  • The 404 page is shown using 404.php
  • Everything else is shown using index.php

While this is okay for most of the content, some site owners would like a bit more specialisation for various post types. We can do this by continuing to build out pages according to the hierarchy:

  • font-page.php for a custom homepage design
  • single.php for individual blog posts
  • page.php for individual pages
  • archive.php for cataloguing posts by date
  • home.php for cataloguing the latest posts

Sidenote: for websites without blog posts (like static brochureware sites), many of these blog-specific pages might not be necessary. But it’s still a good idea to build them out anyway.

There are other secondary page templates that get increasingly more specific to the type of post or page being shown, but the templates we have created here cover the whole spectrum of WordPress’ information-display capabilities.

Editor Style

WordPress has a great feature that enhances the content creation experience: a custom Editor Style:

Apart from affecting the post content appeareance in the editor, this will make the CSS class definitions from the file available in the Styles list box of the TinyMCE editor and able to be assigned to the content.

To make our theme’s styles visible in the editor, we need to do two things:

  • Create a stylesheet called editor-style.css with all the typographic styles that can be used
  • Enqueue that stylesheet for use in the editor using the add_editor_style() hook

This instantly makes the editor a better analogue for how the content will ultimately appear when published:

The TinyMCE Editor without a custom Editor Style
The TinyMCE Editor without a custom Editor Style
The TinyMCE Editor with a custom Editor Style added to reflect the eventual page appearance.
The TinyMCE Editor with a custom Editor Style added to reflect the eventual page appearance.

Is The Theme Complete Yet?

Let’s take stock of what features this theme boasts now:

  • Dynamic title
  • Valid HTML5
  • Dynamic body content
  • Fully-completed metadata
  • Responsive design
  • Specifically-designed page templates
  • Search page
  • 404 page
  • Widgets
  • Sidebars
  • Menus
  • Editor style

This feature set would almost certainly be appropriate for authors who are developing a niche site with somewhat controllable ranges of content. If created for free or as an internal project, our theme should be basically sufficient for most site owners’ needs — and should cater to most basic site visitors.

At this point, many WordPress developers could categorise this theme as complete. But it is not sufficient for all purposes.

To be better than good enough, we should go further and add in features that would make our theme hold its own next to a professionally custom-coded website with all the bells and whistles. After all, that is the point of using a CMS like WordPress: to get the benefits of having a high-quality website without having to actually make it from scratch.

Level 5: Bells And Whistles

Internationalisation

Since themes are general-purpose pieces of software, they need to be able to handle all the different needs of different users around the globe. This means we need to support left-to-right text encodings as well as other languages.

RTL Support

Adding right-to-left text support is easy. All we need to do is add a file called rtl.css to our theme’s directory. This will automatically get enqueued when the page is loaded by a visitor whose browser language displays text from left-to-right.

The contents of this file should include direction-specific overrides:

This should make the website appear more or less correctly in the reverse direction:

Explicitly defining RTL styles will almost always give better results than making the browser try to handle it by itself.
Explicitly defining RTL styles will almost always give better results than making the browser try to handle it by itself.

Adding Translation Support

The 2012 WordPress Survey revealed that more than two-thirds of WordPress users live outside the USA, so it is a good idea to add i18n and l10n functionality to any WordPress theme.

The process can be quite long, so read about it in the following article:

How To Localize A WordPress Theme by Raelene Morey

Print Stylesheet

Like RTL support, adding support for print-specific styles is done with a dedicated stylesheet, called print.css.

We add that to the theme’s root directory and then add a snippet to the Functions File to enqueue the stylesheet, but only use it for printing:

HTML5 Markup Opt-In

The web is always forwards-compatible by design, but that doesn’t mean that best practices don’t evolve. WordPress allows theme authors to opt-in to using newer HTML5-based features like special markup for search forms, comment forms, comment lists, gallery and caption.

To activate these extra features, we inform the WordPress engine through the Functions File that our theme is willing to accept HTML5-specific markup for various sections and features:

You should opt-in to as many of the new HTML5-specific features as possible so browsers can leverage these new technologies in the best ways they can. This gives the end-user a better browsing experience and your theme becomes that much better for it.

Sidenote: the generated markup might be different to your original content, so be sure to check that your styles still apply correctly and make any adjustments to the new markup and content as needed.

Is The Theme Complete Yet?

In Level 4, we created a fairly comprehensive theme with many useful features, but could still fall flat when faced with the complexities of real-world usage.

Now however, our theme boasts the following extras:

  • Specific styles and appearance for printers and RTL users
  • i18n and l10n support for non-English-speaking site owners
  • More semantic, modern HTML5-based widgets and forms

This distinction makes the theme suitable for almost any website and should be the benchmark for WordPress theme developers to attain for any professionally produced work.

This is what it takes to produce a WordPress theme that is commercially satisfactory, for all users in all countries, on all devices. If you’ve created a theme that meets or exceeds this level of comprehensiveness, you can confidently consider it complete!

 


 

Bonus Level: Distribution Compliance

If you want to let other people use a theme you’ve created, you can submit it to a registry or store. The WordPress theme gallery is the best place to submit your theme if it can be used for free, but beware that successful submissions must follow the guidelines.

Additionally, if you wish to sell your theme, some theme sellers like ThemeForest have even stricter acceptance criteria than the WordPress theme gallery, so ensure that your theme meets or exceeds these requirements.

Together with the features presented in this case study, any theme you create can be a great example of how complete any WordPress theme can truly be.

Use Flux Standard Actions for HTTP PATCH

The canonical way to RESTfully apply a set of changes to a resource is through the use of the HTTP PATCH method.

Although a lot has been said about how to use other HTTP verbs, the community has written comparatively less about
PATCH for probably these two reasons:

  1. It didn’t make it into the HTTP/1.1 spec. It wasn’t until 2010 that PATCH was solidified into an RFC, so many APIs and frameworks had to be updated to accommodate for the newcomer. For example, AngularJS didn’t support it for nearly 4 years!
  2. The spec goes through a lot of effort defining what to say, but not how to say it.

The Head-In-Sand Approach To RFC Authorship

A key point in the spec was underscoring the difference between PUT and PATCH. Specifically, PUT payloads include a snapshot of the whole resource’s new identity, while PATCH must contain instructions on how to modify the server’s existing version of the resource.

Side note: Anyone who says PATCH payloads are supposed to be a snippet of the resource’s modifications is wrong, and apparently also an idiot.

The spec reasons that since a resource can be anything, the onus is on the information architect to define some sort of custom DSL to tell the server what to do:

It is expected that different patch document formats will be appropriate for different types of resources…Therefore, there is no single default patch document format that implementations are required to support.

This unopinionated stance was meant to empower the server programmers to implement the most appropriate patch format for each resource type. The idea was that given the freedom to do so, everybody would do it right, every time.

Of course that didn’t happen.

Same Same, But Different

The ambiguity in the spec has led to wildly different (and of course, incompatible) implementations across each server, even when the resource types are identical.

Every blogging CMS API can implement a perfectly RESTful endpoint for updating a blog post with PATCH, but each one of them will do it an unnecessarily different way because there’s no standard, no best practices that describe a good way to represent atomically updating a resource over HTTP.

What application developers really need is a common way to structure a HTTP PATCH request. This will pave the way for reducing implementation fragmentation, which will lead to:

  • Greater skills transference: easier to switch from one project to another without having to learn more unique implementations.
  • Increased certifiability: easier to confirm that the work is correct.
  • Better resource allocation: no need to design a new patch format, existing implementations can be reused.

So what would put us on the right track towards more unified HTTP PATCHes? There’s a few options:

  1. Use JSON Patch
  2. Get together and come up with something new
  3. Re-purpose some existing standard or format

While JSON Patch is an IETF standard specifically designed to be the missing piece of the standards-based puzzle, it has a few issues:

  • Its standard is not versioned. Any upgradable technology does badly without versions.
  • It doesn’t specify how errors should be communicated outside of HTTP response codes. See HTTP Status Codes Are Not Enough.
  • Adoption rate is very low. This means low community critiques, tutorials and support. This also leads to poor tooling.
  • The baffling JSON Pointer-based path property that treats JSON structures like pseudo-URLs instead of regular dot- and square-bracket-based notation.

It seems like continuing with JSON Patch (option 1) as it currently is will not be good enough.

However, coming up with something brand new is a very high-cost task, especially considering the long tail of significant adoption. It’s likely that without the required order of magnitude improvement, we should move onwards from option 2 and decline to build yet another solution from the ground up.

Personally, I believe the case is strong for the community to evaluate the plausibility of re-purposing an existing format. One such option I think is worth investigating is the JS-based Flux Standard Action.

The Case For FSAs

Flux Standard Actions would be a good starting point for a standardised HTTP PATCH payload for several reasons.

It’s Open Source And Actively Maintained

The spec’s canonical home is on GitHub, where the web community can rally around and contribute meaningful discussion, without needing a position at WHATWG or the IETF.

Since it is actively maintained, problems are rectified quickly and improvements are implemented in short cycles.

The Standard Is Versioned

This increases the strength of the API’s contract and allows developers to sidestep the disadvantages of using non-versioned mutating standards.

It’s A Standard

Though there are pitfalls to designing a standard, the concept still allows for an authority to determine what is correct, and encourage programmers to build their systems in a common way. Roy Fielding actually noted during the development of RFC 5789 that it takes too long for individual entities to come to an agreement on best practice.

Side note: if Github Flavored Markdown is considered
a standard, then FSA’s spec is too.

It’s Already Popular

FSAs are the de-facto method of dispatching requests to change a resource in React-land.

And, the number of React users grows, the FSA community gains a lot of support, resources and more.

It’s Simple

The spec is very small and requires only a few minutes to read the entire thing. Compare it with RFC 5789, it’s associated errata and other supplementary resources (including the mandatory RFC 6902) and you’ll find that gravitating towards the simple option is preferable.

The Tooling Is Better

There already exists a number of resources for working with FSAs quickly and efficiently. This lets the community leverage the best work and help get things done more effectively.

The Payload Scales Both Ways

Very tiny instructions need only one property: type. This means that if the server knows what to do with a resource given very simple instructions, the client can send minimal data.

On the other hand if you need a very complicated PATCH, the payload field can be as large as is appropriate for your task.

Errors Are A First-Class Concept

Most of an API’s code goes to handling errors because there’s only one successful path, and a basically unlimited number of error paths.

Incidentally, this is the reason why headphones spend more time tangled than straight.

FSAs make sure that any client consuming your API will always know when an error occurs, and will get good information to debug it. Combine this with a great error standard and any developer consuming your API will almost enjoy receiving errors.

In Conclusion

Since incompatible implementations and fragmentation really sucks, the web community needs to gather its collective will and wisdom and move towards unified, common ways to do things.

The more we do the same stuff the same way, the better we’ll all be for it. Using Flux Standard Actions as the payload in HTTP PATCH requests could be the right way to go.

5 Useful JavaScript Array Methods

JavaScript’s in-built Array type is as useful as it is powerful. However, there’s always some particular thing you need to do with an array and the language can’t do it with a built-in method.

In the spirit of sharing, here’s 5 that I use in my projects to speed up development and make my code more self explanatory:

Get The Last Item

Returns the last item in the array.

Definition

function getLastItem(theArray) {
    return theArray[theArray.length - 1];
}

Usage

let stereotypes = [
    'Groundskeeper Willie',
    'Fat Tony',
    'Cletus',
    'Comic Book Guy'
];

console.log(
    getLastItem(stereotypes)
);
// 'Comic Book Guy'

Remove Any Element

If you have ever had to remove a specific item from an array, the the programming can be unusually low-level and your intentions non-obvious to the next programmer who reads your code. This function will remove the first occurrence of a specified item or value.

This method returns the remaining items in the array. Note that this doesn’t immutably return a new array, it modifies the array itself.

Definition

function removeElement(theArray, whichElement) {
    var elementIndex = theArray.indexOf(whichElement);
    if (theArray.indexOf(whichElement) !== -1) {
        theArray.splice(elementIndex, 1);
    }
    return theArray;
}

Usage

let stereotypes = [
    'Groundskeeper Willie', 
    'Fat Tony', 
    'Cletus',
    'Comic Book Guy'
];

let mostHilariousStereotype = stereotypes[2];
console.log(
    mostHilariousStereotype
);
// 'Cletus'

removeElement(stereotypes, mostHilariousStereotype);
console.log(
    stereotypes
);
// ['Groundskeeper Willie', 'Fat Tony', 'Comic Book Guy'];

Push If Not Present

This method will push the provided argument value to the array if it’s not currently present in the array itself. If the provided argument value is already present in the array, the call does nothing.

This method returns the new values in the array. Note that this can modify the original array, so it’s not immutable.

Definition

function pushIfNotPresent(theArray, element) {
        if (theArray.indexOf(element) === -1) {
            theArray.push(element);
        }
        return theArray;
    };

Usage

let stereotypes = [
    'Groundskeeper Willie', 
    'Fat Tony', 
    'Cletus',
    'Comic Book Guy'
];

pushIfNotPresent(stereotypes, 'The Rich Texan');
console.log(
    stereotypes
);
// -&gt ['Groundskeeper Willie', 'Fat Tony', 'Cletus', 'Comic Book Guy', 'The Rich Texan'];
// ('The Rich Texan' was not already in the array, so it was successfully added.)

pushIfNotPresent(stereotypes, 'Fat Tony');
console.log(
    stereotypes
);
// ['Groundskeeper Willie', 'Fat Tony', 'Cletus', 'Comic Book Guy', 'The Rich Texan'];
// ('Fat Tony' was already in the array, so this method call had no effect.)

Retrieve Unique Values

This one comes from Pedro L on StackOverflow.

This method immutably returns an array of values from the called array, but without any of the duplicated values. Each value will only appear once.

Definition

function getUniques(theArray) {
    return theArray.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
}

Usage

let thingsToRemember = [
    'Dental Plan',
    'Lisa Needs Braces',
    'Dental Plan',
    'Lisa Needs Braces'
    'Dental Plan',
    'Lisa Needs Braces'
];

console.log(
    getUniques(thingsToRemember)
);
// ['Dental Plan', 'Lisa Needs Braces']

Replace Contents

Sometimes you need to completely change what’s in an array without losing its reference. This will remove all the items out of an array and re-fills it with new values.

This method returns the new values in the array. It modifies the original array and is not immutable.

Definition

/**
 * Mutably replaces all the items in the array with `newValues`.
 *
 * @param {Array} theArray - the original array we're working with
 * @param {*|Array} newValues - can be a single item (so the array will now be [thing] or list of new items to become the array's new contents.
 * @returns {Array} - Returns `theArray` (the array modified in-place)
 */
function replaceValues(theArray, newValues) {
    if ((newValues instanceof Array) === false) {
        newValues = [newValues];
    }

    /**
     * Remove all the current items
     */
    theArray.splice(0, theArray.length);

    /**
     * call `splice` again, but this time it inserts each value of `newValues`
     */
    theArray.splice.apply(
        theArray,
        /**
         * [0,0] is the first two arguments of `Array.splice`, and each newValues item is passed as an argument
         * afterwards.
         */
        [0,0].concat(newValues)
    );

    return theArray;
}

Usage

let menuItems = [
    'Krusty Burger with cheese',
    'Krusty partially gelatinated nondairy gum-based beverages'
];

replaceItems(menuItems, [
    'Quarter Pounder with cheese',
    'Shakes'
]);

console.log(menuItems);
// [ 'Quarter Pounder with cheese', 'Shakes']

Feel free to use these methods for your own project, or even make some sort of SuperArray class. Also, if you’ve written any other Array functions that get common use, be sure to let me know!


Note: an earlier version of this article presented these methods as extensions to the Array.prototype object. Even though I warned that I did this for display purposes only, I saw instances of verbatim copying.

Please remember, augmenting a built-in data type should be reserved for advanced use only!

A Practical SASS Project Structure

This is an overview of how I structure the `scss` folder of my web projects:

Overview

Directory Structure

/scss
    /1_utils
    /2_exernal
    /3_elements
    /4_form
    /5_sections
    /6_modules
    /7_pages
    _project-settings.scss
    _shame.scss
    legacy-screen.scss
    screen.scss
    print.scss

The Philosophy

The idea is that splitting files is cheap and modularisation is king. Nothing should be included that doesn’t need to be and the cascade is maintained. In practice, this means that rules go from general to specific.

The print stylesheet (`print.scss`) is a first-class citizen and is just as easy to create and maintain as the main screen stylesheet (`screen.scss`). Old-browser hacks and legacy-IE workarounds only get sent to those browsers with `legacy-screen.scss` leaving the main stylesheet free and modern.

When support for legacy browsers is dropped, `legacy-screen.scss` can be removed and the world keeps spinning without a hitch.

Maintaining the Cascade

The selectors and targets of the partials in each folder are more specific and brand-coupled than those in the preceding folder.

For example, the styles in `/4_form/_buttons.scss` would declare some general styles for various button classes, but specific button instances like `.signup-button` would go in the more specific `/6_modules/_signup-form.scss` file. If the signup form needs to be slightly modified for each page that it is presented on, page-level overrides are defined in `/7_pages`. If the `body` element has a class hook, the CSS could appear as follows:

`/4_form/_buttons.scss`:
button[type=”submit”] {
    /* basic button styles */
}
`/6_modules/_signup-form.scss`:
.signup-button {
    /* specific signup-form-based overrides */
}

`/7_pages/_weekly-promo.scss`:

.pg-weekly-promo {
    .signup-button {
        /* page-specific modifiers */
    }
}

After a few years of refinement, I’m confident enough to consider this to be an effective methodology for several reasons:

  • When things change, only the things that are affected by the change need to be modified e.g: when the Weekly Promo page is retired, the signup form module styles never need to be altered; the page-specific overrides can simply be removed.
  • When investigating bugs, the intended scope of a rule is self-evident: if a rule needs to be altered, the selector itself indicates which SASS file needs to be opened for editing.
  • Keeps single-use modifiers out of the generalised class definitions. If your `<li>`s need to have `font-weight: bold` only in the Features List, the code for it should only live in `/6_modules/_features-list.scss`.
  • Permits cross-project code re-use: every web project I work on needs a similar set of boilerplate code like a clearfix definition, removing the default margin from the `<body>` and even things like sticky footers. These can all be flawlessly re-used with simple, single-purpose classes like `/1_utils/_mixins.scss` and `/3_elements/_footer.scss`.

Usage Breakdown

Here’s how this SASS project structure actually works.

The Root-Level Output Files

All the partials and folders eventually compile down into three files: `screen.css`, `legacy-screen.css` and `print.css` created by their respective SASS files in the root of the folder. Each file is filled with a bunch of `@import`s so that each can independently use only what is needs. For example, `print.scss` probably has no use for `/3_elements/_video.scss` so it simply isn’t imported. Each of the files import the partials in the order that they’re needed, as close to the numerical order that the folder structure uses.

The `_project-settings.scss` partial is imported at the top, as the very first partial because it sets up global variables that the rest of the SASS files use.

`_shame.scss` is kept at the root level as a constant reminder to get in there and clean it up, putting things where they need to go. It is imported at the very bottom.

Note to SASS beginners: the reason that `_shame` and `_project-settings` begin their filenames with an underscore (`_`) but `screen`, `legacy-screen` and `print` do not is explained here.

1_utils

Files in this folder generally do not output any code, they define things like colour variables, breakpoints, mixins and placeholders.

2_external

Files in this folder are styles from external sources like:

  • Icon fonts
  • jQuery plugins
  • CSS frameworks & grid systems

It is important to remember that you should keep the contents of these files as close to the authors’ original versions as possible, overriding styles in other partials written by you. This keeps the original files replaceable and allows for easy updating / diffing when a new version of their file comes out.

Common exceptions to this rule include:

  • Stripping out unneeded rules and styles that will never get used
  • Reducing selector specificity when your overrides are getting too strong
  • Namespacing their code with your own

3_elements

Files in this folder are strictly used to set default element styles. This means things like `<html>` styles go in `_html.scss` and basic list styles go in `_lists.scss`.

I always have the following file called `_all.scss` for the `*` selector:

* {
    box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
}

Another rule of thumb is that styles for table elements—`<table>`, `<tr>`, `<td>`, etc.—can all go into a single `_table.scss` file. Additionally, styles for `<h1>` to `<h6>` elements can all go into `_headers.scss`.

4_form

Files in this folder define the basic styles for form elements and input controls. Aside from the basic `_form.scss`, there’s things like `_select.scss`, `_buttons.scss` and `_checkbox.scss`. Custom form elements like drag-n-drop modules and on-off toggles should be defined in `/6_modules`.

Styles for specific forms like signup forms, contact forms and so on should go into:

  • `/5_sections` if the form is significantly large
  • `/6_modules` if the form is not significantly large, but appears on more than one page
  • `/7_pages` in the partial for the page it appears on if it only appears once on the site

5_sections

This is a somewhat difficult folder to define. Things that are ‘sections’ on a website can often be styled up with dedicated HTML5 selector elements (e.g.: the <header> section gets styled in `/3_elements/_header.scss` but sometimes you have more project-specific sections that need be defined like `_quiz-section.scss` or `_comments-area.scss`. These appear in this folder.

6_modules

If you’re used to building CSS components with Atomic Design, modules are known to you as ‘molecules’—bigger than single elements, but smaller than sections. These are the things that can appear in multiple places throughout your site or app and generally have a single purpose. For example:

  • Search Form
  • Search Result Item
  • Contact Form
  • Scoreboard
  • Gallery
  • Testimonial
  • Grid System

In general, if a module only appears once on a single page, it should probably be defined in the page style. If it gets used in multiple places, refactor it out as its own discrete module.

7_pages

Files in this folder contain page-specific styles and overrides that use a CSS hook on the `<body>` or `<main>` element. As mentioned above, if a module only appears once on a single page, it should probably be defined in the page style.

If you have pages that share layouts, this is still the folder to define their styles but instead of duplicating code in both `_about-us.scss` and `_current-specials.scss`, you can use a more generic selector like `_two-column-page.scss` or `_gallery-page.scss`.

Wrapping Up

Over the last few years I have refined my SASS architecture methodology down to what I’ve written here and I haven’t had any major troubles with it. It is compatible with other architecture like grid systems, BEM and SMACSS and is as non-opinionated as possible.

Getting to a particular rule is easy because the folder structure mimics the scope of the ruleset and the sphere of influence that each rule is given is well defined and doesn’t lead to any nasty surprises.

Sometimes the modules folder can contain many more partials than the other folders, but haven’t come across any significant issues with knowing where to find something when I need to.

Keeping many small, single-purpose files is great for maintainability, self-documentation and code reuse; plus source maps practically hotlink to the specific spot you’re debugging.

If you have any suggestions or ideas to improve this SASS project structure, please let me know!