嗨,我是 Fly,用 Ruby 寫 Chatbot 並挑戰30天分享心得
為確保不會沒靈感
每日含 Ruby 主題文章增加內容
https://github.com/leo424y/clean-code-ruby
讓你好好測試
Bad:
programmer_output = [
{
name: 'Uncle Bobby',
lines_of_code: 500
}, {
name: 'Suzie Q',
lines_of_code: 1500
}, {
name: 'Jimmy Gosling',
lines_of_code: 150
}, {
name: 'Grace Hopper',
lines_of_code: 1000
}
]
total_output = 0
programmer_output.each do |output|
total_output += output[:lines_of_code]
end
Good:
programmer_output = [
{
name: 'Uncle Bobby',
lines_of_code: 500
}, {
name: 'Suzie Q',
lines_of_code: 1500
}, {
name: 'Jimmy Gosling',
lines_of_code: 150
}, {
name: 'Grace Hopper',
lines_of_code: 1000
}
]
INITIAL_VALUE = 0
total_output = programmer_output
.reduce(INITIAL_VALUE) { |acc, output| acc + output[:lines_of_code] }
### 包裝判斷式
**Bad:**
```ruby
if params[:message].present? && params[:recipient].present?
# ...
end
Good:
def send_message?(params)
params[:message].present? && params[:recipient].present?
end
if send_message?(params)
# ...
end
Bad:
if !genres.blank?
# ...
end
Good:
unless genres.blank?
# ...
end
# or
if genres.present?
# ...
end
Bad:
class Airplane
# ...
def cruising_altitude
case @type
when '777'
max_altitude - passenger_count
when 'Air Force One'
max_altitude
when 'Cessna'
max_altitude - fuel_expenditure
end
end
end
Good:
class Airplane
# ...
end
class Boeing777 < Airplane
# ...
def cruising_altitude
max_altitude - passenger_count
end
end
class AirForceOne < Airplane
# ...
def cruising_altitude
max_altitude
end
end
class Cessna < Airplane
# ...
def cruising_altitude
max_altitude - fuel_expenditure
end
end