【发布时间】:2012-05-01 16:59:24
【问题描述】:
我已经得到了一些代码来查找问题和可以改进和改变的东西(这是一个家庭作业,但这个问题与任务本身无关),部分代码是:
Function CheckIfSameCell(ByVal FirstCellPosition As CellReference, ByVal SecondCellPosition As CellReference) As Boolean
Dim InSameCell As Boolean
InSameCell = False
If FirstCellPosition.NoOfCellsSouth = SecondCellPosition.NoOfCellsSouth And FirstCellPosition.NoOfCellsEast = SecondCellPosition.NoOfCellsEast Then
InSameCell = True
End If
CheckIfSameCell = InSameCell
End Function
我不明白为什么要创建 InSameCell 是变量,而它只能分配给函数名称 CheckIfSameCell?
或者只使用如下的 return 语句?
Function CheckIfSameCell(ByVal FirstCellPosition As CellReference, ByVal SecondCellPosition As CellReference) As Boolean
If FirstCellPosition.NoOfCellsSouth = SecondCellPosition.NoOfCellsSouth And FirstCellPosition.NoOfCellsEast = SecondCellPosition.NoOfCellsEast Then
Return True
End If
Return False
End Function
我可以理解不直接返回If语句中的表达式,以增加可读性。
我知道为函数名称分配返回值不会退出函数,而 Return 会退出,但它只是一个人的风格,还是第一个版本有什么优势(IMO,第二个更具可读性)?
【问题讨论】:
-
我认为这只是个人选择而不是规则,而且一些程序员遵循他们从书本或网上阅读的模式。我也更喜欢第二个代码(我以这种风格编写代码),它易于阅读并使用更少的变量。
-
您的建议是更好的正确方法,使用
return而不是使用函数名。之前的函数可能是用 VB6 编写的,然后转换为 .Net,因为 VB6 是这样编码的 -
当切换到结构化编程时,一个规则是each function should have a single exit point。引用链接页面,“现在结构化编程早已赢得了胜利,没有人特别关心这一点了”。
-
对于仍然发现这个古董的人来说,“混乱”的唯一正当原因是有人习惯了 VB6(或从它升级的代码),不需要
InSameCell,不需要If,应该只返回值,And也应该替换为AndAlso,并删除ByVal