iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 29
0
自我挑戰組

易讀程式之美學系列 第 29

抽離不相關子問題--3

專案專屬功能

以下是取自企業意見調查網站的例子,Python 程式碼建立了新的 Business 物件並依序設定了name、url 及date_created:

business = Business()
business.name = request.POST["name"]

url_path_name = business.name.lower()
url_path_name = re.sub(r"['\.]","",url_path_name)
url_path_name = re.sub(r"['^a-z0-9]+","-",url_path_name)
url_path_name = url_path_name.strip("-")
business.url = "/biz/" + url_path_name

business.date_created = datetime.datetime.utcnow()
business.save_to_database()

這段程式碼中不相關的子問題是:「將名稱轉換為合法 URL 」,能夠輕易抽離這段程式碼,這麼做之後甚至可以預先編譯好正規表示式(並給予比較好讀的名稱):

CHARS_TO_REMOVE = re.compile(r"['\.]+")
CHARS_TO_DASH = re.compile(r"['^a-z0-9]")

def make_url_friendly(text):

text = text.lower()
text = CHARS_TO_REMOVE.sub('',text)
text = CHARS_TO_DASH.sub('-',text)
return text.strip("-")

現在原先的程式碼有更加「一致」的模式:

business = Business()
business.name = request.POST["name"]
business.url = "/biz/" + make_url_friend(business.name)
business.date_created = datetime.datetime.utcnow()
business.save_to_database

程式碼讀起來更省力,不再被使用正規表示式的字串處理細節而干擾。

Reference

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

上一篇
抽離不相關子問題--2
下一篇
抽離不相關子問題--4
系列文
易讀程式之美學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言