Last active
August 18, 2016 08:57
-
-
Save carlescliment/01a9b23f2fc11f6373c4752f39eedc52 to your computer and use it in GitHub Desktop.
alternatives to multiple if/elses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using a hash | |
def classes_for(path) | |
classes = { | |
'facilities' => %w(instalaciones listado), | |
'offers' => %w(oferta academica), | |
'teachers' => %w(claustro), | |
'news' => %w(actualidad), | |
'agenda' => %w(actualidad) | |
} | |
classes.key?(path) ? classes[path] : [] | |
end | |
# Moving the conditionals to "matchers" | |
# Consider the following code | |
def teach(person) | |
if person.age < 1.year || some_complex_condition | |
# the way babies are taught... | |
elsif person.age.between(7, 14) || some_complex_condition | |
# the way youngsters are taught... | |
elsif person.age > 18 || some_other_complex_condition | |
# the way adults are taught... | |
end | |
end | |
# The solution above may be okay for simple code or for code that is not expected to be changed often. | |
# In order to make it more extensible or able to add conditions in runtime, it may be worth to split | |
# the responsibilities. | |
class BabiesTeacher | |
def can_teach?(person) | |
person.age < 1.year || some_complex_condition | |
end | |
def teach(person) | |
# the way babies are taught... | |
end | |
end | |
class YoungstersTeacher | |
def can_teach?(person) | |
person.age.between(7, 14) || some_complex_condition | |
end | |
def teach(person) | |
# the way youngsters are taught... | |
end | |
end | |
class AdultsTeacher | |
def can_teach?(person) | |
person.age > 18 || some_other_complex_condition | |
end | |
def teach(person) | |
# the way adults are taught... | |
end | |
end | |
teachers = [BabiesTeacher.new, YoungstersTeacher.new, AdultsTeacher.new] | |
teachers.each do |teacher| | |
teacher.teach(person) if teacher.can_teach?(person) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment