iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 22
0
自我挑戰組

易讀程式之美學系列 第 22

分解巨大表示式--2

利用笛摩根定律

這是將布林表示示改寫成等等價表示式的方式:

  1. not (a or b or c) <=> (not a) and (not b) and (not c)
  2. not (a and b and c) <=> (not a) or (not b) or (not c)

如果記不起來,簡單記法是「把 not 分配到各項,在反轉 not/or
利用這定律讓布林更有可讀性:

if (!(file_exists && !is_protected)) Error("Sorry,could not read file.");

可以改寫成:

if (!(file_exists || is_protected)) Error("Sorry,could not read file.");

誤用捷徑邏輯

assert((|(bucket = Findbucket(key))) || !bucket->IsOccupied());

即使是一行程式碼, 許多程式設計師都得稍做思考才能理解他的行為,改成下列程式會容易理解的多:

bucket = FindBucket(key);
if (bucket != NULL) assert(!bucket->IsOccupied());

雖然有2行程式碼,行為也完全相同,但容易理解的多。

重要概念
注意寫法「很酷」的程式碼---經常會對後續使用使用程式的人造成困擾

Reference

  • <<易讀程式之美學-提升程式碼可讀性的簡單法則 >>(The Art of Readable Code)

上一篇
分解巨大表示式--1
下一篇
分解巨大表示式--3
系列文
易讀程式之美學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言