我知道这篇文章很古老,但格式良好的代码永远不会过时。
我在所有程序中都使用此模板。有些人不喜欢冗长的代码和 cmets,但作为一个经常需要更新自 90 年代中期以来未触及的存储过程的人,我可以告诉您编写格式良好且注释繁多的代码的价值。许多内容尽可能简洁,有时可能需要数天才能掌握程序的意图。通过简单地阅读一段代码很容易看出它在做什么,但在没有适当注释的情况下理解代码的意图要困难得多(有时甚至是不可能的)。
解释它就像你正在引导一个初级开发人员通过它。假设阅读它的人对它正在处理的功能领域知之甚少,并且对 SQL 的理解有限。为什么?很多时候,人们必须查看程序才能理解它们,即使他们无意或不打算修改它们。
/***************************************************************************************************
Procedure: dbo.usp_DoSomeStuff
Create Date: 2018-01-25
Author: Joe Expert
Description: Verbose description of what the query does goes here. Be specific and don't be
afraid to say too much. More is better, than less, every single time. Think about
"what, when, where, how and why" when authoring a description.
Call by: [schema.usp_ProcThatCallsThis]
[Application Name]
[Job]
[PLC/Interface]
Affected table(s): [schema.TableModifiedByProc1]
[schema.TableModifiedByProc2]
Used By: Functional Area this is use in, for example, Payroll, Accounting, Finance
Parameter(s): @param1 - description and usage
@param2 - description and usage
Usage: EXEC dbo.usp_DoSomeStuff
@param1 = 1,
@param2 = 3,
@param3 = 2
Additional notes or caveats about this object, like where is can and cannot be run, or
gotchas to watch for when using it.
****************************************************************************************************
SUMMARY OF CHANGES
Date(yyyy-mm-dd) Author Comments
------------------- ------------------- ------------------------------------------------------------
2012-04-27 John Usdaworkhur Move Z <-> X was done in a single step. Warehouse does not
allow this. Converted to two step process.
Z <-> 7 <-> X
1) move class Z to class 7
2) move class 7 to class X
2018-03-22 Maan Widaplan General formatting and added header information.
2018-03-22 Maan Widaplan Added logic to automatically Move G <-> H after 12 months.
***************************************************************************************************/
除了这个标头之外,您的代码还应该有很好的注释和从上到下的概述。向主要功能部分添加注释块,例如:
/***********************************
** Process all new Inventory records
** Verify quantities and mark as
** available to ship.
************************************/
添加大量内联 cmets,解释除最基本的标准外的所有标准,并始终格式化代码以提高可读性。长的垂直缩进页面比宽的短页面更好,并且当其他人支持您的代码时,可以更容易地查看代码块的开始和结束位置。有时,宽的、非缩进的代码更具可读性。如果是这样,请使用它,但仅在必要时使用。
UPDATE Pallets
SET class_code = 'X'
WHERE
AND class_code != 'D'
AND class_code = 'Z'
AND historical = 'N'
AND quantity > 0
AND GETDATE() > DATEADD(minute, 30, creation_date)
AND pallet_id IN ( -- Only update pallets that we've created an Adjustment record for
SELECT Adjust_ID
FROM Adjustments
WHERE
AdjustmentStatus = 0
AND RecID > @MaxAdjNumber
编辑
我最近放弃了横幅样式的注释块,因为随着代码的不断更新,顶部和底部的 cmets 很容易分离。您最终可能会在注释块中使用逻辑上独立的代码,这些代码说它们属于一起,这会产生比它解决的问题更多的问题。我已经开始围绕与 BEGIN ... END 块一起属于的多个语句部分,并将我的流 cmets 放在每个语句的第一行旁边。这样做的好处是让您可以折叠代码块并能够清楚地阅读高级流 cmets,并且当您打开一个部分时,您将能够对其中的各个语句执行相同的操作。这也非常适合高度嵌套的代码级别。当您的 proc 开始进入 200-400 行范围并且不会将任何行批量添加到已经很长的过程中时,这是非常宝贵的。
展开
已折叠