When you sit down to write some code, your first goal is to make it work. Your second goal is to make it elegant.
Refactoring is the process of editing or rewriting your code so that the code is more elegant, faster, and generally, easier to maintain, without changing how the code functions.
Refactoring can take many forms and what you do entirely depends on what needs improving. Here is a short list of ways to you could improve your code:
Make the code more dynamic
When you are writing a program for the first time, the easiest thing to do is to hard-code everything. What this means is that much of the data will be explicitly programmed into the code, rather than allowing the program to dynamically generate its own data.
Hard coding data values is great when you need to do something quick and dirty, but can be be deleterious to your program in the long term. When your code isn’t dynamic, every time you want to add a new feature or functionality to the site, even if an identical feature already exists, you have to write a whole new set of code. Time to refactor!
Make the code reusable
Making your code reusable often goes hand in hand with making it dynamic. The goal here is to make the wheel once. So let’s say that your site has slideshows on every page. You could write a new slideshow function for each one, but you should only write one slideshow function and use it to power all of the slideshows. Go refactor!
Make the code faster
Coding is all about logic. The question you have to ask yourself is whether your logic is slow and circuitous, or fast and furious? Are you accomplishing your goal with the fewest steps possible? If not, it’s time to refactor!
Make the code shorter
Making your code faster usually results in less code. And less code usually makes your code faster. That said, there are instances where more code isn’t slowing your computer down, but it is slowing you down. It’s time to refactor!
Make the code easier to read
All coding languages serve as translators: they translate human instructions into a language that computers can understand. That said, they should be optimized for humans! If a non-coder can’t read your code and get some idea of what it’s doing (maybe you are using obscure variables and nonsensical method or function names), it’s time to refactor!
How else can you improve your code? Tell us!