之前以为伪代码的作用仅仅是让程序的逻辑更加清晰,并且只能给自己看。今天看了code complete有亮点非常深的体会。首先是伪代码的作用不仅仅是给写代码的使用,可以把它直接作为程序的注释。看一个例子,看看如何写出好的伪代码,并且如何使用它。
increment resource number by 1
allocate a dlg struct using malloc
if malloc() returns NULL then return 1
invoke OSrsrc_init to initialize a resource for the operating system
*hRsrcPtr = resource number
return 0
这是一个写的非常不好的伪代码,首先逻辑不清晰,写的程序让人不明白。作为伪代码,包含了c语言的代码细节*hRsrcPtr。还有return 0,这些实现细节完全可以封装起来。修改后的代码如下:
Keep track of current number of resources in use
If another resource is available
Allocate a dialog box structure
If a dialog box structure could be allocated
Note that one more resource is in use
Initialize the resource
Store the resource number at the location provided by the caller
Endif
Endif
Return TRUE if a new resource was created; else return FALSE
可以看到使用这个代码实现的语言可以不仅用c实现,用其它语言的开发者看到这个伪代码也可以很轻松的实现。原因在于它的封装程度高了一层,用自然语言实现,并且逻辑更清晰。
为什么使用伪代码了?可以看到伪代码的实现和修改非常容易,相当于在语言级别上的编程,不必设计语言细节。在语言细节上的修改代价是非常大的,但是在伪代码层次修改容易。
将伪代码如何修改直接作为注释使用了?再看一个例子:
如何使用这些伪代码了?
- /* This routine outputs an error message based on an error code
- supplied by the calling routine. The way it outputs the message
- depends on the current processing state, which it retrieves
- on its own. It returns a value indicating success or failure.
- */
- Status ReportErrorMessage(
- ErrorCode errorToReport
- ) {
- // set the default status to "fail"
- Status errorMessageStatus = Status_Failure;
- // look up the message based on the error code
- Message errorMessage = LookupErrorMessage( errorToReport );
- // if the error code is valid
- if ( errorMessage.ValidCode() ) {
- // determine the processing method
- ProcessingMethod errorProcessingMethod = CurrentProcessingMethod();
- // if doing interactive processing, display the error message
- // interactively and declare success
- if ( errorProcessingMethod == ProcessingMethod_Interactive ) {
- DisplayInteractiveMessage( errorMessage.Text() );
- errorMessageStatus = Status_Success;
- }
- // if doing command line processing, log the error message to the
- // command line and declare success
- else if ( errorProcessingMethod == ProcessingMethod_CommandLine ) {
- CommandLine messageLog;
- if ( messageLog.Status() == CommandLineStatus_Ok ) {
- messageLog.AddToMessageQueue( errorMessage.Text() );
- messageLog.FlushMessageQueue();
- errorMessageStatus = Status_Success;
- }
- else {
- // can't do anything because the routine is already error processing
- }
- else {
- // can't do anything because the routine is already error processing
- }
- }
- // if the error code isn't valid, notify the user that an
- // internal error has been detected
- else {
- DisplayInteractiveMessage(
- "Internal Error: Invalid error code in ReportErrorMessage()"
- );
- }
- // return status information
- return errorMessageStatus;
- }
直接将伪代码作为注释,空白处添加语言代码。这样的过程极好的利用了伪代码,也可以让编程的思路更加清晰。其本质是将过程拆分,也是分割的思想。初看code complete这段的确给我震惊的感觉。伪代码的直接利用。
总结下就是先写出伪代码,作为理清思路发现错误一个帮助,然后再直接将伪代码作为注释在注释处写出语言代码。例子中是c++代码。