代码功能
使用软件定时器定时50ms 轮询执行ADC采集并处理。
优化前代码:
void
task_adc_sampling_callback(void *user_data)
{
static uint8_t into_times = 0;
switch (into_times)
{
case 0:
{
/* Charging line voltage detection and processing */
}
break;
case 1:
{
/* Battery temporature detection and processing */
}
break;
case 2:
{
/* Battery power percentage detection and processing */
}
break;
default: break;
}
into_times++;
if (into_times >= 3)
{
into_times = 0;
}
}
优化后代码:
void
task_adc_sampling_callback(void *user_data)
{
static uint8_t into_times = 0;
into_times++;
if (into_times > 3) ///< 3: Number of switch..case branches
{
into_times = 1;
}
printf("into_times is : %d \n", into_times); //for debugging
switch (into_times)
{
case 1:
{
/* Charging line voltage detection and processing */
}
break;
case 2:
{
/* Battery temporature detection and processing */
}
break;
case 3:
{
/* Battery power percentage detection and processing */
}
break;
default: break;
}
}
优化修改了什么
调整了变量into_times的使用规则。
优化后效果
- 对变量的使用进行集中,代码的可读性得到了增强。(那种上下文呼应的变量,让人看到定义时不知道有什么用,看到调用和修改时不知道下文是否还有修改,一个变量出现在函数任何位置都有可能。在理解代码时需要时时注意,细心观察。甚至有些无效变量仍存在于函数中影响理解)
- 在函数开头显眼位置添加了一条关键注释,把握住了函数最关键的变量,维护也变得容易。
- 顺便说一下:如果再将函数的注释结合起来,对于函数的理解(实现方式 与 调用规则)时间大大缩短,可以提升些效率。结合上分层架构与模块化,对于工程师之间代码复用也有一定程度的帮助。
- 顺便说一下:局部变量有时名字起得很简短,需要联系使用 来了解其用途,不知道变量用途而变量拖沓得使用范围很大,理解不顺畅的代码你放心去用吗,比如对于开源代码软件定时器,虽然阅读有点儿难度,但掌握了一定知识后理解起来相当顺畅。