ruby - 将代码语句放在大括号中是好的编程习惯吗?

标签 ruby qt qtruby

在我一生中阅读的所有源代码中,我从未见过这样做的地方。如果它被认为是糟糕的编程习惯,那么必须有一个我无法理解的原因。另外,我认为它有时会提高可读性而不是恶化它。这是我在我的 ruby​​ 代码中完成的几个地方。

@pushButton.connect(SIGNAL :clicked) do (@select_file ||= Qt::FileDialog.new).show end

(tmr=Qt::Timer.new).connect SIGNAL :timeout do 
  @label.text = Qt::Application.translate("MainWindow", "The time right now is #{Time.now}", nil, Qt::Application::UnicodeUTF8)
end 
tmr.start(1000)

最佳答案

尽可能力求简单总是一个好主意,为此最好以直截了当的方式陈述事情。像这样的声明使得很难确定变量的来源,因为它们相当彻底地嵌入到语句中。

在括号内声明作用域变量通常被认为是可以接受的:

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)

我发现最复杂的程序往往看起来最简单,因为它们是由经验丰富的人编写的,他们知道如何以直截了当的方式表达事物。

有趣的是,一些最简单的程序往往是最复杂的,因为它们是由新手编写的,这些新手要么哗众取宠、炫耀,要么将自己挖到一个很深的沟里,并不断地向问题抛出代码以期解决问题

关于ruby - 将代码语句放在大括号中是好的编程习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1907319/

相关文章:

ruby-on-rails - 在 RVM 错误下安装 Gems

Ruby编码练习解决方案(rubymonk)

C++/Qt - 从主窗口打开对话框 - 错误 LNK2019 - LNK2001 : unresolved external symbol

c++ - 谁为 Qt 开发语言绑定(bind)?

ruby - 在 Ruby block 中使用 'return'

ruby - 设置环境变量,无需在字符串和整数之间进行转换

qt - 如何在半透明的QWidget上播放视频?

c++ - QListWidget共享同一个模型

ruby - Ruby 中的 Qt Model/View 编程示例和教程