今天查看自己為《專業嵌入式軟件開發》一書所寫的代碼時發現,個別函數由於沒有引入中間變量,使代碼行既長又不易讀。重構前後的代碼如下所示。
重構前:
if (TIMER_STARTED == _handle->state_) {
timer_handle_t next;
if (g_timer_next == _handle) {
g_timer_next = (timer_handle_t) dll_next (&g_bucket_firing->dll_,
&_handle->node_);
}
next = (timer_handle_t)dll_next
(&g_buckets [_handle->bucket_index_].dll_, &_handle->node_);
if (0 != next) {
next->round_ += _handle->round_;
}
dll_remove (&g_buckets [_handle->bucket_index_].dll_, &_handle->node_);
if (g_buckets [_handle->bucket_index_].reentrance_ > 0) {
g_bucket_firing->level_ ++;
}
}
重構後:
if (TIMER_STARTED == _handle->state_) {
timer_handle_t next;
bucket_t *p_bucket = &g_buckets [_handle->bucket_index_];
if (g_timer_next == _handle) {
g_timer_next = (timer_handle_t) dll_next (&g_bucket_firing->dll_,
&_handle->node_);
}
next = (timer_handle_t)dll_next (&p_bucket->dll_, &_handle->node_);
if (0 != next) {
next->round_ += _handle->round_;
}
dll_remove (&p_bucket->dll_, &_handle->node_);
if (p_bucket->reentrance_ > 0) {
g_bucket_firing->level_ ++;
}
}
作者 李雲