将代码语句放在括号中是一种很好的编程习惯吗?

pot*_*lee 2 ruby qt qtruby

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

@pushButton.connect(SIGNAL :clicked) do (@select_file ||= Qt::FileDialog.new).show end
Run Code Online (Sandbox Code Playgroud)

(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)
Run Code Online (Sandbox Code Playgroud)

tad*_*man 9

在任何可能的地方努力追求简洁总是一个好主意,为此,最好以直截了当的方式陈述事物.这样的声明使得很难确定变量的来源,因为它们在语句中被完全嵌入.

在括号内声明范围变量通常被认为是可接受的:

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
Run Code Online (Sandbox Code Playgroud)

一个更详细的版本实际上有影响:

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
Run Code Online (Sandbox Code Playgroud)

能够通过程序进行扫描并且非常清楚地看到所有变量的声明,这总是很好.隐藏事物除了挫败人们之外没有任何其他目的.

就你可以逃脱多少而言,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
Run Code Online (Sandbox Code Playgroud)

第二:

# 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)
Run Code Online (Sandbox Code Playgroud)

我发现最复杂的程序通常看起来最简单,因为它们是由具有丰富经验的人编写的,他们知道如何以直接的方式表达事物.

有趣的是,一些最简单的程序往往是最复杂的,因为它们是由新手编写的,他们要么是哗众取宠,要么炫耀或正在深陷自己的深沟,并且为了解决这个问题而不断抛出代码.


tro*_*skn 6

我觉得这很难读.我希望它稍微冗长一点,但更清楚:

tmr = Qt::Timer.new
tmr.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)
Run Code Online (Sandbox Code Playgroud)


Ste*_* B. 5

将太多逻辑语句塞入1行的代码很难阅读,因为读者基本上必须将它在大脑中展开成类似于troelskn的答案的陈述.

其他原因是它的可读性较低:

  • 它使行长度超过大多数文本编辑器窗口的边界.
  • 它模糊了调试时可能需要查看的各个步骤.