In many ways, the idea seems simple, but it is easy to forget. When you are writing a program repeating code happens quite often. Sometimes it happens in various sections of your program so it isn’t always quick to recognize. Other times, we are just in a rush to get something done without thinking it through so code gets cut and pasted several times with few if any changes.
While, we have all made those mistakes, it makes your life easier to step back and find a way to fix it. Often, the fix involves pulling out a chunk of code and turning it into a function or a method. Other times, it involves rethinking why you are doing things the way you are doing them. Still other times, finding better ways to use the language will solve the problem.
A common fix in Swift is to replace a collection of if statements with a case statement. That doesn’t solve all of the issues, but it helps out more often than you’d think. As I am writing this, I can think of several areas in my own code that would be helped by this piece of advice alone.
If you can avoid the repetition, it will make your code more readable. But, beyond that, it will also make your code easier to update. It is far easier to change one function than to track down all the areas that you might have used the same code in order to make a simple change. Just think of how many potential bugs could be introduced by missing one or two areas.
Another way to avoid repetition is to set up constants for values that get used throughout your program. This allows you to change values in many places by only setting one variable. I use this many times with various values such as a scale modifier, or animation constants. It allows you to stay more consistent through the code, while also allowing you to make quick changes. If the value is limited in scope, then try to define it in that scope if at all possible. Also, make sure that you use variable names that are descriptive and make sense. It’s far easier to figure out why you used spriteScaler than a number 4.5 when you are reading the code.
So, take a few minutes to look through some of your code to find areas that you repeated yourself and take the time to fix that issue. You will thank yourself in the future.