Refactoring CSS: Technique, Regression Testing And Upkeep (Half 2)

No Comments

In Half 1, we’ve lined the negative effects of low-quality CSS codebase on end-users, improvement groups, and administration. Sustaining, extending, and dealing with the low-quality codebase is troublesome and infrequently requires extra time and sources. Earlier than mentioning the refactoring proposal to the administration and stakeholders, it may be helpful to again up the suggestion with some laborious knowledge in regards to the codebase well being — not solely to persuade the administration division, but in addition have a measurable aim for the refactoring course of.

Let’s assume that administration has permitted the CSS refactoring venture. The event workforce has analyzed and pinpointed the weaknesses within the CSS codebase and has set goal targets for the refactor (file measurement, specificity, shade definitions, and so forth). On this article, we’ll take a deep dive into the refactoring course of itself, and canopy incremental refactoring technique, visible regression testing, and sustaining the refactored codebase.

Preparation And Planning

Earlier than beginning the refactoring course of, the workforce must go over the codebase points and CSS well being audit knowledge (CSS file measurement, selector complexity, duplicated properties, and declarations, and so forth.) and focus on particular person points about how you can strategy them and what challenges to count on. These points and challenges are particular to the codebase and may make the refactoring course of or testing troublesome. As concluded within the earlier article, it’s essential to determine inside guidelines and codebase requirements and hold them documented to be sure that the workforce is on the identical web page and has a extra unified and standardized strategy to refactoring.

The workforce additionally wants to stipulate the person refactoring duties and set the deadlines for finishing the refactoring venture, taking into consideration present duties and ensuring that refactoring venture doesn’t stop the workforce from addressing pressing duties or engaged on deliberate options. Earlier than estimating the time length and workload of the refactoring venture, the workforce must seek the advice of with the administration in regards to the short-term plans and alter their estimates and workload primarily based on the deliberate options and common upkeep procedures.

In contrast to common options and bug fixes, the refactoring course of yields little to no seen and measurable adjustments on the entrance finish, and administration can not hold monitor of the progress on their very own. It’s essential to determine clear communication to maintain the administration and different venture stakeholders up to date on the refactoring progress and outcomes. On-line collaborative workspace instruments like Miro or MURAL can be used for efficient communication and collaboration between the workforce members and administration, in addition to a fast and easy activity administration device.

Christoph Reinartz identified the significance of transparency and clear communication whereas the workforce at trivago was engaged on the CSS refactoring venture.

“Communication and clearly making the progress and any upcoming points seen to the entire firm had been our solely weapon. We determined to construct up a quite simple Kanban board, established a venture stand-up and a venture Slack channel, and saved administration and the corporate up-to-date through our inside social solid community.”

Probably the most essential aspect of planning the refactoring course of is to maintain the CSS refactoring activity scope as small as attainable. This makes the duties extra manageable, and simpler to check and combine.

Harry Roberts refers to those duties as “refactoring tunnels”. For instance, refactoring your complete codebase to comply with the BEM methodology abruptly can yield an enormous enchancment to the codebase and the event course of. This may seem to be a easy search-and-replace activity at first. Nevertheless, this activity impacts all parts on each web page (excessive scope) and the workforce can not “see the sunshine on the finish of the tunnel” straight away; plenty of issues can break within the course of and sudden points can decelerate the progress and nobody can inform when the duty goes to be completed. The workforce can spend days or even weeks engaged on it and danger hitting a wall, accumulate extra technical debt, or making the codebase even much less wholesome. The workforce finally ends up both giving up on the duty of beginning over, losing time and sources within the course of.

Against this, enhancing simply the navigation part CSS is a smaller scope activity and is way more manageable and doable. It’s also simpler to check and confirm. This activity may be carried out in a couple of days. Even with potential points and challenges that decelerate the duty, there’s a excessive likelihood of success. The workforce can all the time “see the tip of the tunnel” whereas they’re engaged on the duty as a result of they know the duty might be accomplished as soon as the part has been refactored and all points associated to the part have been mounted.

Lastly, the workforce must agree on the refactoring technique and regression testing technique. That is the place the refactoring course of will get difficult — refactoring ought to be as streamlined as attainable and shouldn’t introduce any regressions or bugs.

Let’s dive into one of many handiest CSS refactoring methods and see how we will use it to enhance the codebase shortly and successfully.

Incremental Refactoring Technique

Refactoring is a difficult course of that’s way more advanced than merely deleting the legacy code and changing it with the refactored code. There’s additionally the matter of integrating the refactored codebase with the legacy codebase and avoiding regressions, unintended code deletions, stopping stylesheet conflicts, and so forth. To keep away from these points, I’d suggest utilizing an incremental (or granular) refactoring technique.

For my part, this is without doubt one of the most secure, most obvious, and most advisable CSS refactoring methods I’ve come throughout to this point. Harry Roberts has outlined this technique in 2017. and it has been my private go-to CSS refactoring technique since I first heard about it.

Let’s go over this technique step-by-step.

Step 1: Decide A Element And Develop It In Isolation

This technique depends on particular person duties having low scope, which means that we must always refactor the venture part by part. It’s advisable to start out with low-scope duties (particular person parts) after which transfer onto higher-scoped duties (international types).

Relying on the venture construction and CSS selectors, particular person part types include a mixture of part (class) types and international (wide-ranging aspect) types. Each part types and international types may be the supply of the codebase points and may have to be refactored.

Let’s check out the extra frequent CSS codebase points which may have an effect on a single part. Element (class) selectors may be too advanced, troublesome to reuse, or can have excessive specificity and implement the precise markup or construction. International (aspect) selectors may be grasping and leak undesirable types into a number of parts which have to be undone with high-specificity part selectors.

After selecting a part to refactor (a lower-scoped activity), we have to develop it in an remoted setting away from the legacy code, its weaknesses, and conflicting selectors. That is additionally an excellent alternative to enhance the HTML markup, take away pointless nestings, use higher CSS class names, use ARIA attributes, and so forth.

You don’t need to exit of your technique to arrange a complete construct system for this, you possibly can even use CodePen to rebuild the person parts. To keep away from conflicts with the legacy class names and to separate the refactored code from the legacy code extra clearly, we’ll use an rf- prefix on CSS class title selectors.

Step 2: Merge With The Legacy Codebase And Repair Bugs

As soon as we’ve completed rebuilding the part in an remoted setting, we have to change the legacy HTML markup with refactored markup (new HTML construction, class names, attributes, and so forth.) and add the refactored part CSS alongside the legacy CSS.

We don’t need to act too swiftly and take away legacy types straight away. By making too many adjustments concurrently, we’ll lose monitor of the problems which may occur because of the conflicting codebases and a number of adjustments. For now, let’s change the markup and add refactored CSS to the prevailing codebase and see what occurs. Remember that refactored CSS ought to have the .rf- prefix of their class names to stop conflicts with the legacy codebase.

Legacy part CSS and international types may cause sudden side-effects and leak undesirable types into the refactored part. Refactored codebase may be lacking the defective CSS which was required to undo these side-effects. Resulting from these types having a wider attain and presumably affecting different parts, we can not merely edit the problematic code instantly. We have to use a unique strategy to sort out these conflicts.

We have to create a separate CSS file, which we will title overrides.css or defend.css which is able to include hacky, high-specificity code that combats the undesirable leaked types from the legacy codebase.

overrides.css which is able to include high-specificity selectors which be sure that the refactored codebase works with the legacy codebase. That is solely a short lived file and it will likely be eliminated as soon as the legacy code is deleted. For now, add the high-specificity fashion overrides to unset the types utilized by legacy types and take a look at if every thing is working as anticipated.

Should you discover any points, examine if the refactored part is lacking any types by going again to the remoted setting or if some other types are leaking into the part and have to be overridden. If the part seems to be and works as anticipated after including these overrides, take away the legacy code for the refactored part and examine if any points occur. Take away associated hacky code from overrides.css and take a look at once more.

Relying on the case, you most likely gained’t have the ability to take away each override straight away. For instance, if the difficulty lies inside a world aspect selector which leaks types into different parts that additionally have to be refactored. For these circumstances, we gained’t danger increasing the scope of the duty and the pull request however moderately wait till all parts have been refactored and sort out the high-scope duties after we’ve eliminated the identical fashion dependency from all different parts.

In a approach, you possibly can deal with the overrides.css file as your makeshift TODO record for refactoring grasping and wide-reaching aspect selectors. You must also take into account updating the duty board to incorporate the newly uncovered points. Be certain so as to add helpful feedback within the overrides.css file so different workforce members are on the identical web page and immediately know why the override has been utilized and in response to which selector.

/* overrides.css */
/* Resets dimensions enforced by “.sidebar > div” in “sidebar.css” */
.sidebar > .card {
min-width: 0;
}

/* Resets font measurement enforced by “.hero-container” in “hero.css”*/
.card {
font-size: 18px;
}

Step 3: Check, Merge And Repeat

As soon as the refactored part has been efficiently built-in with the legacy codebase, create a Pull Request and run an automatic visible regression take a look at to catch any points which may have gone unnoticed and repair them earlier than merging them into one of many principal git branches. Visible regression testing may be handled because the final line of protection earlier than merging the person pull requests. We’ll cowl visible regression testing in additional element in one of many upcoming sections of this text.

Now rinse and repeat these three steps till the codebase has been refactored and overrides.css is empty and may be safely eliminated.

Step 4: Transferring From Parts To International Types

Let’s assume that we now have refactored all particular person low-scoped parts and all that’s left within the overrides.css file are associated to international wide-reaching aspect selectors. It is a very practical case, talking from the expertise, as many CSS points are attributable to wide-reaching aspect selectors leaking types into a number of parts.

By tackling the person parts first and shielding them from the worldwide CSS side-effects utilizing overrides.css file, we’ve made these higher-scoped duties way more manageable and fewer dangerous to do. We will transfer onto refactoring international CSS types extra safely than earlier than and take away duplicated types from the person parts and changing them with basic aspect types and utilities — buttons, hyperlinks, pictures, containers, inputs, grids, and so forth. By doing so, we’re going to incrementally take away the code from our makeshift TODO overrides.css file and duplicated code repeated in a number of parts.

Let’s apply the identical three steps of the incremental refactoring technique, beginning by growing and testing the types in isolation.

Subsequent, we have to add the refactored international types to the codebase. We would encounter the identical points when merging the 2 codebases and we will add the mandatory overrides within the overrides.css. Nevertheless, this time, we will count on that as we’re steadily eradicating legacy types, we may also have the ability to steadily take away overrides that we’ve launched to fight these undesirable side-effects.

The draw back of growing parts in isolation may be present in aspect types which can be shared between a number of parts — fashion information parts like buttons, inputs, headings, and so forth. When growing these in isolation from the legacy codebase, we don’t have entry to the legacy fashion information. Moreover, we don’t need to create these dependencies between the legacy codebase and refactored codebase.

That’s the reason it’s simpler to take away the duplicated code blocks and transfer these types into separate, extra basic fashion information parts and selectors afterward. It permits us to handle these adjustments proper on the finish and with the decrease danger as we’re working with a a lot more healthy and constant codebase, as an alternative of the messy, inconsistent, and buggy legacy codebase. After all, any unintended side-effects and bugs can nonetheless occur and these ought to be caught with the visible regression testing instruments which we’ll cowl in one of many following sections of the article.

When the codebase has been fully refactored and we’ve eliminated all makeshift TODO objects from the overrides.css file, we will safely take away it and we’re left with the refactored and improved CSS codebase.

Incremental CSS Refactoring Instance

Let’s use the incremental refactoring technique to refactor a easy web page that consists of a title aspect and two card parts in a grid part. Every card aspect consists of a picture, title, subtitle, description, and a button and is positioned in a 2-column grid with horizontal and vertical spacing.

Relying on the venture, testing instruments don’t have to be advanced or refined to be efficient. Whereas engaged on refactoring the Sundance Institute’s CSS codebase, the event workforce used a easy static fashion information web page generated by Jekyll to check the refactored parts.

“One unintended consequence of executing the refactor in abstraction on a Jekyll occasion was that we might now publish it to Github pages as a dwelling fashion information. This has turn into a useful useful resource for our dev workforce and for exterior distributors to reference.”

As soon as the CSS refactor duties have been accomplished and the refactored code is prepared for manufacturing, the workforce may take into account doing an A/B take a look at to examine the impact of the refactored codebase on customers. For instance, if the aim of the refactoring course of was to scale back the general CSS file measurement, the A/B take a look at can doubtlessly yield important enhancements for cell customers, and these outcomes can be useful to venture stakeholders and administration. That’s precisely how the workforce at Trivago approached the deployment of their large-scale refactoring venture.

“(…) we had been capable of launch the technical migration as an A/B Check. We examined the migration for one week, with constructive outcomes on cell units the place mobile-first paid out and accepted the migration after solely 4 weeks.”

Holding Observe Of Refactoring Progress

Kanban board, GitHub points, GitHub venture board, and normal venture administration instruments can do an incredible job of holding monitor of the refactoring progress. Nevertheless, relying on the instruments and the way the venture is organized, it could be troublesome to estimate the progress on a per-page foundation or do a fast examine on which parts have to be refactored.

That is the place our .rf-prefixed CSS courses are available. Harry Roberts has talked in regards to the advantages of utilizing the prefix intimately. The underside line is — not solely do these courses enable builders to clearly separate the refactored CSS codebase from the legacy codebase, but in addition to shortly present the progress to the venture managers and different venture stakeholders on a per-page foundation.

For instance, administration could determine to check the consequences of the refactored codebase early by deploying solely the refactored homepage code and they’d need to know when the homepage parts might be refactored and prepared for A/B testing.

As an alternative of losing a while evaluating the homepage parts with the obtainable duties on the Kanban board, builders can simply briefly add the next types to focus on the refactored parts which have the rf- prefix of their class names, and the parts that have to be refactored. That approach, they’ll reorganize the duties and prioritize refactoring homepage parts.

/* Highlights all refactored parts */
[class*=”rf-“] {
define: 5px stable inexperienced;
}

/* Highlights all parts that havent been refactored */
[class]:not([class*=”rf-“]),
physique *:not([class]) {
define: 5px stable crimson;
}

Sustaining The Refactored Codebase

After the refactoring venture has been accomplished, the workforce wants to verify to keep up the codebase well being for the foreseeable future — new options might be developed, some new options may even be rushed and produce technical debt, numerous bugfixes may also be developed, and so forth. All in all, the event workforce must be sure that the codebase well being stays secure so long as they’re answerable for the codebase.

Technical debt which can lead to doubtlessly defective CSS code ought to be remoted, documented, and carried out in a separate CSS file which is commonly named as disgrace.css.

It’s essential to doc the principles and finest practices that had been established and utilized through the refactoring initiatives. Having these guidelines in writing permits for standardized code critiques, quicker venture onboarding for brand new workforce members, simpler venture handoff, and so forth.

A number of the guidelines and finest practices can be enforced and documented with automated code-checking instruments like stylelint. Andrey Sitnik, the creator of widely-used CSS improvement instruments like PostCSS and Autoprefixer, has famous how computerized linting instruments could make code critiques and onboarding simpler and fewer traumatic.

“Nevertheless, computerized linting shouldn’t be the one purpose to undertake Stylelint in your venture. It may be extraordinarily useful for onboarding new builders on the workforce: plenty of time (and nerves!) are wasted on code critiques till junior builders are absolutely conscious of accepted code requirements and finest practices. Stylelint could make this course of a lot much less traumatic for everybody.”

Moreover, the workforce can create a Pull Request template and embrace the guidelines of requirements and finest practices and a hyperlink to the venture code guidelines doc in order that the builders making the Pull Request can examine the code themselves and be sure that it follows the agreed requirements and finest practices.

Conclusion

Incremental refactoring technique is without doubt one of the most secure and most advisable approaches in relation to refactoring CSS. The event workforce must refactor the codebase part by part to make sure that the duties have a low scope and are manageable. Particular person parts have to be then developed in isolation — away from the defective code — after which merged with the prevailing codebase. The problems that will come up from the conflicting codebases may be solved by including a short lived CSS file that incorporates all the mandatory overrides to take away the conflicts in CSS types. After that, legacy code for the goal part may be eliminated and the method continues till all parts have been refactored and till the non permanent CSS file which incorporates the overrides is empty.

Visible regression testing instruments like Percy and Chromatic can be utilized for testing and to detect any regressions and undesirable adjustments on the Pull Request degree, so builders can repair these points earlier than the refactored code is deployed to the stay website.

Builders can use A/B testing and use monitoring instruments to be sure that the refactoring doesn’t negatively have an effect on efficiency and person expertise earlier than lastly launching the refactored venture on a stay website. Builders may also want to make sure that the agreed requirements and finest practices are used on the venture continues to keep up the codebase well being and high quality sooner or later.

References

Refactoring CSS With out Dropping Your Thoughts,” Harry Roberts (Video, WeAreDevelopers Convention, 2017)
Massive Scale CSS Refactoring At Trivago,” Christoph Reinartz
Refactoring Tunnels,” Harry Roberts
Sundance.org Design System And CSS Refactor,” Kirby Yardley
5 Years Of PostCSS: State Of The Union,” Andrey Sitnik

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment