最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Day 21 Clean Code Ruby

XAMPP下载 admin 623浏览 0评论
 函數式地開發吧
讓你好好測試

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

转载请注明:XAMPP中文组官网 » Day 21 Clean Code Ruby

您必须 登录 才能发表评论!