当前位置:编程学习 > 网站相关 >>

让编程变得简洁

写这个题目是因为看《c专家编程》得到的一些启发。

有的时候我们写代码,洋洋洒洒几千行,最后调试的时候错误百出,这当然说的是我自己的状态。而如何避免这种情况呢,今天在《c专家编程》里找到了一些东西。

我想再赞叹一句,《c专家编程》里到处都有真知灼见。

看一下这一段:

A colleague had to write a program that at one point stored filenames and information about each file. The data was stored in a table of structs, and he decided to use hash lookup. Here's where the coding for debuggability came in. He didn't try to get every part of the program working in one swell foop. He got it working for the simplest case first, by making the hash function always return the constant zero. The function looked like this:

/* hash_file: Placeholder for more sophisticated future
routine */ 
int hash_filename (char *s) 
{
 return 0; 
}
The code that called it looked like this:
/* 
* find_file: Locate a previously created file descriptor or 
*     make a new one if necessary. 
*/ 
file find_filename (char *s) 
{
 int hash_value = hash_filename(s); 
 file f; 
 for (f = file_hash_table[hash_value]; f != NIL;f=f->flink) { e
  if (strcmp(f->fname, s) == SAME) {
   return f; 
  } 
 } 
 /* file not found, so make a new one: */ 
 f = allocate_file(s); 
 f->flink = file_hash_table[hash_value]; 
 file_hash_table[hash_value] = f; 
 return f; 
}
The effect was as though a hash table was not used; all the elements would be stored in a linked list off element zero. This made it simple to debug, because you didn't have to calculate where anything really should be. The ace programmer was able to quickly get the rest of the code working because he did not have to worry about the interaction with hashing. When he was satisfied that the main routines worked perfectly, he took some performance measurements, and decided to activate the hash function. This was a two-line change in a single function. Here's the current version involving, as he put it, "brain, pain, and gain". 

int hash_filename (char *s) 
{
 int length = strlen(s); 
 return (length+4*(s[0]+4*s[length/2])) % FILE_HASH; 
}
Sometimes taking the time to break a programming problem into smaller parts is the fastest way of solving it. 

这是作者的一位同事编写一个程序的过程,用到的是散列表。他把程序的开发分成了几个部分,从最简单的开始,让最小程序能够运行,然后在此基础上添加细节,那么我们每步出现的问题就一目了然。

最后一句话是这样的:

“有时候,花点时间把编程问题分解成几个部分往往是解决它的最快方法。”

让我们记住它。
作者:Jerryz

补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,