One of the golden rules for programming is to not repeat yourself. You have so many tools in your arsenal: for, while, do loops, methods etc
In [[Ruby on Rails]] if a variable is used only once, then it can better be avoided altogether. However, a wrong abstraction can cause a lot more headache as compared to a slight duplication.
The "Don't Repeat Yourself" (DRY) principle in Ruby encourages developers to avoid duplicating code and promotes the use of abstraction and modularization. Here are a few examples that illustrate this philosophy:
1. Avoiding Duplicate Logic:
```ruby
# Bad: Duplicated logic
def calculate_area(length, width)
length * width
end
def calculate_perimeter(length, width)
2 * (length + width)
end
# Good: Reusing logic through abstraction
def calculate_area(length, width)
length * width
end
def calculate_perimeter(length, width)
2 * calculate_sum(length, width)
end
def calculate_sum(a, b)
a + b
end
```
1. Extracting Reusable Methods:
```ruby
# Bad: Duplicate code in multiple places
def greeting(name)
puts "Hello, #{name}!"
end
greeting("John")
greeting("Jane")
# Good: Reusing code through extracted methods
def greeting(name)
puts "Hello, #{name}!"
end
greet("John")
greet("Jane")
def greet(name)
greeting(name)
end
```
1. Utilizing Inheritance:
```ruby
# Bad: Repeating similar code across different classes
class Dog
def speak
puts "Woof!"
end
def walk
puts "Walking..."
end
# ...
end
class Cat
def speak
puts "Meow!"
end
def walk
puts "Walking..."
end
# ...
end
# Good: Abstracting common behavior into a superclass or module
module AnimalActions
def speak(sound)
puts sound.to_s.capitalize + '!'
end
def walk(action = 'Walking')
puts action + '...'
end
# ...
end
class Dog
include AnimalActions
def initialize
speak(:woof)
walk
end
# ...
end
class Cat
include AnimalActions
def initialize
speak(:meow)
walk
end
# ...
end
```
By following the DRY principle, developers can reduce code duplication, improve code maintainability, and make their programs more flexible to changes.
![[Learning Ruby#^jaujcf]]