Sometimes (ok, most times), in order to get the ball rolling on an aspect of a project, I’ll do a bad job. I’ll create a component or module in the code that works, but is a bit of a mess. It’s probably not the best idea- my intention is always to go back and optimize, but it doesn’t always work out that way.
But when it does- when I have the time and permission to go back and clean up the code- it’s great! I get to review how I started out, see what I did wrong, and do my best to fix it. It’s a great way to improve.
As an example- I’m working on an Angular 2 project right now. We’re still getting things started, but at the very beginning, I created a few custom page interaction components- a loading ‘spinner’, a notification pop up, and a modal window. They all worked, but each had flaws. The most glaring was that each directly manipulated the DOM- a no-no in Angular.
And after going back to refactor, I now know why. When dependency injection is done right (another thing I had to refactor), it’s a beautiful thing. But when it’s not, it can create loading order and time issues. When I cleaned up DI in the app, those 3 custom components broke. All of a sudden, the browser shouted ‘cannot call style on null’.
And that was because I was manipulating the style directly in a component. To show the loading spinner, I called spinner.show()- but all that really did was grab the spinner element and change display:none to display:block. Now that everything was loading correctly, that spinner div didn’t exist when the component loaded (the template hadn’t been injected yet), so the app took the train to errortown.
So, instead of grabbing each element and working the old JS way, I realized I could just bind to native properties in the template. The spinner.show() function would just update a boolean flag (showing) to true. That flag is bound to the [hidden] property on my spinner div, and I was back in business.
I try to read a lot about web development and programming, and many times have see the advice that premature optimization is the root of all evil. But when it comes to refactoring- not necessarily for performance, but for functionality and ease of use/updating- there really doesn’t seem to be a bad time to start.