一個變數指一件事,函數作用後是另件事了
Bad:
# Global variable referenced by following function.
# If we had another function that used this name, now it’d be an array and it could break it.
$name = ‘Ryan McDermott’
def split_into_first_and_last_name
$name = $name.split(‘ ‘)
end
split_into_first_and_last_name()
puts $name # [‘Ryan’, ‘McDermott’]
Good:
def split_into_first_and_last_name(name)
name.split(‘ ‘)
end
name = ‘Ryan McDermott’
new_name = split_into_first_and_last_name(name)
puts name # ‘Ryan McDermott’
puts new_name # [‘Ryan’, ‘McDermott’]
再避免副作用
再次避免搞混變數及函式
Bad:
def add_item_to_cart(cart, item)
cart.push(item: item, time: Time.now)
end
Good:
def add_item_to_cart(cart, item)
cart + [{ item: item, time: Time.now }]
end
转载请注明:XAMPP中文组官网 » Day 20 Function – Prevent Side Effect – Clean Code Ruby