menu

Refactor or Rewrite

By: Chris McIlvoy / December 1st 2022 / Optimization
Refactor or Rewrite

It would be great if every time we build a new feature, we got it right the first time. However, that is not how it works.

As developers, we are consistently working against the clock. Occasionally, we can find ourselves thrown in the hurry of sprint--building custom components with complex requirements.

And, at times, we can look back in review and ask, "how did the iteration go down this path?"

It is 100% fair to say there are always small improvements to make to the initial implementation. And, it is also completely acceptable to stop and question:

"Should we scrap, refactor or rewrite?"

Sunk costs should not drive a decision to stay the course. If a reflective review of the work points to better approaches, then leverage the knowledge--and potentially, even portions of the code--to get it right.

Example

Recently, we had to develop a light folder browse component. An initial stab at the HTML was done quickly, without much consideration to the hierarchy. The poor semantics led to an even poorer implementation in the CSS, which then forced a ton of unnecessary JavaScript (JS) to compensate for the short-falls in HTML/CSS.

We can see in this "before & after" example of the HTML, that the structure really got off to a bad start. Choosing not to leverage HTML's List structures left a scenario where many ad-hoc classes were required to try to replicate to a hierarchy.

Code Screenshot

50% reduction in lines of code plus a much easier to read structure

This, in turn, led to a CSS rat's nest and tons of JS click events to produce a result that could not even meet our standards.

Lessons Learned

  1. Always focus on clean and simple semantic HTML. Spend time and research the right DOM element structure. Read the MDN docs.
  2. CSS is an expansive language--especially when you add in SCSS. Avoid JS if you can tackle the requirement in CSS.
  3. Get your HTML/CSS structure laid out before you start introducing JS to get UI functionality in place.
  4. Challenge yourself to avoid JS even, and see how far you can get the experience without JS enhancements.