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

Day 19 – Clean Code Ruby

XAMPP下载 admin 681浏览 0评论
 Functions
函式參數最多兩個,或使 Simbol
Bad:

def create_menu(title, body, button_text, cancellable)
# …
end
Good:

def create_menu(title:, body:, button_text:, cancellable:)
# …
end

create_menu(
title: ‘Foo’,
body: ‘Bar’,
button_text: ‘Baz’,
cancellable: true
)
單一職責
Bad:

def email_clients(clients)
clients.each do |client|
client_record = database.lookup(client)
email(client) if client_record.active?
end
end
Good:

def email_active_clients(clients)
clients
.select(&method(:active_client?))
.each(&method(:email))
end

def active_client?(client)
client_record = database.lookup(client)
client_record.active?
end
明確表示職責
Bad:

def add_to_date(date, month)
# …
end

date = DateTime.now

# It’s hard to to tell from the function name what is added
add_to_date(date, 1)
Good:

def add_month_to_date(date, month)
# …
end

date = DateTime.now
add_month_to_date(date, 1)
抽象最多一層
以便測試

Bad:

def interpret(code)
regexes = [
# …
]

statements = code.split(‘ ‘)
tokens = []
regexes.each do |regex|
statements.each do |statement|
# …
end
end

ast = []
tokens.each do |token|
# lex…
end

result = []
ast.each do |node|
# result.push(…)
end

result
end
Good:

def interpet(code)
tokens = tokenize(code)
ast = lex(tokens)
parse(ast)
end

def tokenize(code)
regexes = [
# …
]

statements = code.split(‘ ‘)
tokens = []
regexes.each do |regex|
statements.each do |statement|
# tokens.push(…)
end
end

tokens
end

def lex(tokens)
ast = []
tokens.each do |token|
# ast.push(…)
end

ast
end

def parse(ast)
result = []
ast.each do |node|
# result.push(…)
end

result
end
別重覆程式
Bad:

def show_developer_list(developers)
developers.each do |developer|
data = {
expected_salary: developer.expected_salary,
experience: developer.experience,
github_link: developer.github_link
}

render(data)
end
end

def show_manager_list(managers)
managers.each do |manager|
data = {
expected_salary: manager.expected_salary,
experience: manager.experience,
portfolio: manager.mba_projects
}

render(data)
end
end
Good:

def show_employee_list(employees)
employees.each do |employee|
data = {
expected_salary: employee.expected_salary,
experience: employee.experience
}

case employee.type
when ‘manager’
data[:portfolio] = employee.mba_projects
when ‘developer’
data[:github_link] = employee.github_link
end

render(data)
end
end
參數不要用旗標
旗標代表會做兩件事以上,一個函數只做一件事

Bad:

def create_file(name, temp)
if temp
fs.create(“./temp/#{name}”)
else
fs.create(name)
end
end
Good:

def create_file(name)
fs.create(name)
end

def create_temp_file(name)
create_file(“./temp/#{name}”)
end

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

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