Keeping it DRY

Melissa Gonzalez
Adventures in Code
Published in
2 min readJul 2, 2017
While it may be a great day to go for a swim, a good programmer knows to keep it DRY!

This week, we learned the importance of keeping your code DRY.

DRY stands for “Don’t Repeat Yourself” and refers to the practice of not repeating code via copying and pasting. That way, if anything needs to change in the future, you only have to make the update in one section rather than finding everywhere you copied and pasted the code.

We learned two methods to be able to use the same codes multiple times: inheritance and modules.

Use inheritance when you have one class that will retain all the functions of another class. The example we learned used Managers as a type of Employee that would inherit all the functions of an employee, but with additional functions.

To set this up, we used the code class Manager < Employee to tell Ruby that any Manager should be able to do anything that an employee can do. We can then add additional functions to the Manager class as necessary.

Another way to keep our code DRY is to use Modules. Modules are simply a set of code that can used to share common methods. It’s generally accepted that modules are named with a capital letter and end with “-able” to describe what the module does. In general, the module should contain functions that are similar and that are generally used together.

The example used in class was to describe the moving actions of cars and bikes. We named the Module “Moveable” since it’s a subset of codes that describe how both the car and bike can move:

module Moveable
def brake
@speed = 0
end

def accelerate
@speed += 10
end

def turn(new_direction)
@direction = new_direction
end
end

It’s important to note when your code is repeating itself, vs when the values just happen to be the same at a particular instead. For example, to start, the initialize method for both car and bike might be that they both start at speed = 0 and direction = 'north'. However we kept the initialize function within each class rather than using a module, since there’s a real possibility of adding different initialize functionalities to each class.

Deciding what’s the same for now versus what’s repetitive code will be something we’ll learn with practice!

--

--

Melissa Gonzalez
Adventures in Code

Aspiring Web Developer. Fitness Enthusiast. Foodie. Beer Lover. Triathlete. Former Research Scientist.