【编程好习惯】引入中间变量使程序更易读

本文出自 “至简李云” 博客,请务必保留此出处http://yunli.blog.51cto.com/831344/859794
今天查看自己为《专业嵌入式软件开发》一书所写的代码时发现,个别函数由于没有引入中间变量,使代码行既长又不易读。重构前后的代码如下所示。
重构前:
  1. if (TIMER_STARTED == _handle->state_) {
  2.    timer_handle_t next;
  3. if (g_timer_next == _handle) {
  4.        g_timer_next = (timer_handle_t) dll_next (&g_bucket_firing->dll_,  
  5.            &_handle->node_);
  6.    }
  7.    next = (timer_handle_t)dll_next  
  8.        (&g_buckets [_handle->bucket_index_].dll_, &_handle->node_);
  9. if (0 != next) {
  10.        next->round_ += _handle->round_;
  11.    }
  12.    dll_remove (&g_buckets [_handle->bucket_index_].dll_, &_handle->node_);
  13. if (g_buckets [_handle->bucket_index_].reentrance_ > 0) {
  14.        g_bucket_firing->level_ ++;
  15.    }
  16. }
重构后:
  1. if (TIMER_STARTED == _handle->state_) {
  2.    timer_handle_t next;
  3. bucket_t *p_bucket = &g_buckets [_handle->bucket_index_];
  4. if (g_timer_next == _handle) {
  5.        g_timer_next = (timer_handle_t) dll_next (&g_bucket_firing->dll_,  
  6.            &_handle->node_);
  7.    }
  8.    next = (timer_handle_t)dll_next (&p_bucket->dll_, &_handle->node_);
  9. if (0 != next) {
  10.        next->round_ += _handle->round_;
  11.    }
  12.    dll_remove (&p_bucket->dll_, &_handle->node_);
  13. if (p_bucket->reentrance_ > 0) {
  14.        g_bucket_firing->level_ ++;
  15.    }
  16. }
阅读更多

没有更多推荐了,返回首页