65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 PDL(编程设计语言)设计和记录您的代码

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.10/5 (10投票s)

2010 年 6 月 27 日

CPOL

2分钟阅读

viewsIcon

65231

了解使用这种简单技术设计和记录代码的好处

引言

我们很多人低估了通过注释进行适当代码文档记录的重要性。当正确使用时,注释可以大大提高函数和例程的可维护性,特别是如果将来有其他开发人员需要查看你的代码。记住你 5 年前编写的例程的意图就很难了,更不用说对你最初打算做什么一无所知的人了。

背景

在阅读《代码大全》(每位开发人员,无论技能水平、年龄或编程语言,都应该拥有一本)时,我发现了一种用于注释例程的方法,它提供的不仅仅是代码注释。

Using the Code

这种方法称为 PDL(编程设计语言)。PDL 的基本思想是在编写任何代码之前,先编写方法的全部注释。一旦注释完成,你就可以用实现来填充空白。

这是一个例子。

Public Function CanUserDrink(ByVal Age As Integer, _
	ByVal HasLicense As Boolean) As Boolean 
    'If the user is of the legal drinking age  
    'If the user has a drivers license 
    'Return success to the caller 
    'Otherwise the user does not have a drivers license 
    'Return Failure to the caller 
    'Otherwise the user is too young 
    'Return Failure to the caller 
End Function 

Public Function CanUserDrink(ByVal Age As Integer, _
	ByVal HasLicense As Boolean) As Boolean 
    'If the user is of the legal drinking age
    If Age > 21 Then 
        'If the user has a drivers license 
        If HasLicense Then 
            'Return success to the caller 
            Return True 
        'Otherwise the user does not have a drivers license 
         Else 
            'Return Failure to the caller 
            Return False  
        End If  
    'Otherwise the user is too young 
    Else  
        'Return Failure to the caller 
        Return False  
    End If 
End Function

这里有几点需要注意:

  • 所有注释都以逻辑方式格式化(缩进)。
  • 使用这种方法时,你首先以高级格式(纯英文)编写注释。
  • 这允许你在高级别抽象下设计例程。
  • 需求使用英文编写,因此例程的设计可以很容易地移植到任何语言。
  • 所有思考工作都提前完成。
  • 剩下的就是在每个注释下填充代码。
  • 用英文编写的注释准确地说明了你需要什么,因此实现起来轻而易举。
  • 由于注释是首先编写的,你可以确信你的所有方法都将得到充分的文档记录。

如果其他开发人员正在阅读你的代码,他可以简单地阅读你的高级注释,直到找到他需要的代码。

关注点

因此,可以看出,使用 PDL 有几个优点:

  • 确保代码始终有文档记录。
  • 允许对例程进行高级别设计,该设计不依赖于特定的编程语言实现(记住注释是纯英文)。
  • 一旦注释完成,编码就变得轻而易举,因为逻辑已经在注释中以纯英文记录下来了。

我希望你发现学习 PDL 像我一样有益。别忘了购买《代码大全》!

下次再见。

历史

  • 2010 年 6 月 27 日:初始发布
© . All rights reserved.