儘可能努力追求簡單總是一個好主意,爲此,最好以直接的方式陳述事情。像這樣的聲明使得很難確定變量來自哪裏,因爲它們完全嵌入語句中。
括號內聲明作用域變量通常被認爲是可以接受的:
if (found = MyModel.find_by_pigeon_id(params[:pigeon_id]))
# Variable 'found' used only within this block
end
# Ruby variables will persist here, but in many languages they are out of scope
一個更詳細的版本實際上已經影響:
found = MyModel.find_by_pigeon_id(params[:pigeon_id])
if (found)
# Variable 'found' can be used here
end
# Implies 'found' may be used here for whatever reason
它總是很高興能夠通過程序掃描,看看,很清楚,所有的變量,因爲他們宣佈。除了挫敗人們之外,隱藏的東西沒有任何其他用途。
從許多其他語言的角度來看,Ruby可以讓你放鬆多少。有些語言會因爲複雜化而嚴厲懲罰你,因爲聲明或鑄造中的小錯誤可能會造成巨大的後果。這並不意味着你應該充分利用每一個機會。
這是我怎麼會倡導實施的第一個例子:
# Ensure that @select_file is defined
@select_file ||= Qt::FileDialog.new
@pushButton.connect(SIGNAL(:clicked)) do
# Block is split out into multiple lines for clarity
@select_file.show
end
第二:
# Simple declaration, variable name inherited from class name, not truncated
timer = Qt::Timer.new
timer.connect(SIGNAL(:timeout)) do
# Long parameter list is broken out into separate lines to make it clear
# what the ordering is. Useful for identifying accidentally missing parameters.
@label.text = Qt::Application.translate(
"MainWindow",
"The time right now is #{Time.now}",
nil,
Qt::Application::UnicodeUTF8
)
end
timer.start(1000)
我發現,最複雜的程序往往看起來最簡單的,因爲他們是由具有豐富經驗的人撰寫,他們知道如何以直接的方式表達內容。
有意思的是,一些最簡單的程序往往是最複雜的,因爲它們是由新手寫的,他們要麼譁衆取寵,要麼展現自我,要麼正在深入挖掘,不斷拋出代碼來解決問題,修復它。