Please enable JavaScript to use CodeHS

CodeHS Glossary


DRY Principle JavaScript

Otherwise known as Don’t Repeat Yourself, this principle is designed to help eliminate repeated code and reduce the complexity of a solution. This principle should be practiced within logical components, as well as, documentation of code. Removing duplication insures single representation which allows for cleaner code that can easily be changed. An example of a program that does not utilize the DRY Principle is: /* This program makes Karel move twice * turn around, and move back */ function start() { moveKarelToEnd(); turnAround(); moveKarelTwice(); } //Duplicate function function moveKarelToEnd() { move(); move(); } //Duplicate function function moveKarelTwice() { move(); move(); } In this example we can see that moveKarelToEnd(); and moveKarelTwice(); serve the exact same function. Instead of two separate functions that contain the same code, only one should be used. An example of a program which utilizes the DRY principle is: /* This program makes Karel move twice * turn around, and move back */ function start() { moveKarelTwice(); turnAround(); moveKarelTwice(); } function moveKarelTwice() { move(); move(); } As you can see, in this program, the function moveKarelTwice(); is being reused, and not duplicated in to a new function.