放假,在读一些书,其中提到《代码大全》一书,所以找来看看(其实手上有英文版,不过懒得去啃英文,因此错过了和这么好的书早点见面的缘分),
把中文版拿来一看,才读了一点点我就被震惊了,所以推荐大家一定要读代《代码大全》这本书,有多么经典随便搜索下评价就可以知道了。
震惊的案例,是因为平时工作中看到一个处理优先级的代码,把优先级的值放到一个数组中,而没有做类似if ... else ...的判断,真的是太经典。
自己写了个demo如下,作为简单的参考,简单的引子。
#include <stdio.h>
#include <stdlib.h>
/*
* 业务类型 serviceType: 775 516 777 258 259
* 优先级权值 priorityLevel : 80 ,100,30,3,30
*/
unsigned int PriorityLevel[5] = { 80,100,30,3,30 };
/* 以表格访问的形式获取业务的优先级的值
*/
unsigned int GetPriorityFromTable(unsigned int serviceType)
{
return PriorityLevel[serviceType%5];
}
/* 以分支的判断的形式获取业务的优先级的值
*/
unsigned int GetPriorityBranchStatments(unsigned int serviceType)
{
unsigned int retVal = 0;
//或者用switch case 语句,但是反正都是做分支判断
if(serviceType == 777 || serviceType == 259)
{
retVal = 30;
}
else if( serviceType == 775)
{
retVal = 80;
}
else if( serviceType == 516)
{
retVal = 100;
}
else if( serviceType == 258 )
{
retVal = 3 ;
}
return retVal ;
}
/*
* 获得一个权值,拿来计算一些东西,这里示范了两种方法,可以第一种的编码风格的优雅,相当的舒服 。
*/
int main( )
{
unsigned int serviceType = 516;
printf("Priority Level %u \n",GetPriorityFromTable(serviceType));
printf("Priority Level %u \n",GetPriorityBranchStatments(serviceType));
}