首页 > 其他分享 >注释的反面教材

注释的反面教材

时间:2022-11-20 23:34:39浏览次数:30  
标签:tempRegValue 可读性 modulation 代码 注释 How 反面教材


都说好注释应该写Why而不是How,这里给个只写How的废话注释作为反面教材。

void SpiritRadioSetModulation(ModulationSelect xModulation)
{
uint8_t tempRegValue;

/* Check the parameters */
s_assert_param(IS_MODULATION_SELECTED(xModulation));

/* Reads the modulation register */
SpiritSpiReadRegisters(MOD0_BASE, 1, &tempRegValue);

/* Mask the other fields and set the modulation type */
tempRegValue &=0x8F;
tempRegValue |= xModulation;

/* Writes the modulation register */
g_xStatus = SpiritSpiWriteRegisters(MOD0_BASE, 1, &tempRegValue);
}

上面这段代码里的注释是不是都是废话呢。典型的为了写注释而写注释,代码本身的可读性已经非常强了,看代码本省就足够理解代码了,何必再写多余的注释?4行注释都是How型注释。所谓How型注释是解释代码是怎么工作的,Why型注释是解释代码为什么要这么写。How型的注释是完全没有必要的。可读性强的代码,阅读代码本省就可以理解代码是怎么工作的,写注释去解释可读性差的代码还不如想想怎么改进代码的可读性呢。优秀的代码应该是自注释的(Self-Documenting Code),就是说代码自己能把自己解释清楚,不用注释来瞎搀和。

  • ​​《避免代码注释的五大理由》​​
  • ​​《五种应该避免的代码注释》​​


标签:tempRegValue,可读性,modulation,代码,注释,How,反面教材
From: https://blog.51cto.com/zoomdy/5872180

相关文章