# Bad
class Person
def be_polite(big_favor)
if big_favor
'Thank you very much'
else
'Thank you'
end
end
end
Person.new.be_polite(true)
Person.new.be_polite(false)
# Good
class Person
def thanks
'Thank you'
end
def much_thanks
'Thank you very much'
end
end
Person.new.much_thanks
Person.new.thanks
# Bad
class Bird
attr_accessor :nailed?, :type
BASE_SPEED = 10
LOAD_FACTOR = 3
def initialize(nailed=false, type=nil)
self.nailed? = nailed
self.type = type
end
def speed
case type
when :european
BASE_SPEED
when :african
BASE_SPEED - LOAD_FACTOR
when :norwegian
nailed? ? 0 : BASE_SPEED
else
0
end
end
end
# Good
class Bird
BASE_SPEED = 10
LOAD_FACTOR = 3
def speed
0
end
end
class EuropeanBird < Bird
def speed
BASE_SPEED
end
end
class AfricanBird < Bird
def speed
BASE_SPEED - LOAD_FACTOR
end
end
class NorwegianBird < Bird
attr_accessor :nailed?
def initialize(nailed)
self.nailed? = nailed
super
end
def speed
nailed? ? 0 : BASE_SPEED
end
end
# Bad
def sum(numbers)
return 0 unless numbers
numbers.reduce(:+)
end
# Good
def sum(numbers=[])
numbers.reduce(:+)
end
# Bad
def horrible(foo, bar, baz)
if foo
if bar
true
end
end
if baz
true
else
false
end
end
# Good
def horrible(foo, bar, baz)
foo && bar || baz
end
# Bad
class Repository
def record_name(id)
DB.find(id).name
end
end
class Finder
def display_record(repository)
name = repository.record_name(123)
return "No name" unless name
name
end
end
# Good
class Repository
def record_name(id, default_name)
result = DB.find(id)
return result.name if result
default_name
end
end
class Finder
def display_record(repository)
repository.record_name(123, 'No name')
end
end