Quora 问答社区的一个开发者投票统计, 程序员最大的难题是: 如何命名 (例如: 给变量, 类, 函数等等), 光是如何命名一项的选票几乎是其它八项的投票结果的总和. 如何给变量命名, 如何让它变得有意义成了程序员不可逾越的难题, 这篇文章参考了 Clean Code , 提供 7 条命名建议, 希望能在取名字的过程中给你带来一些帮助.
以下都是基于 Python3.7 语法
变量
1, 使用有意义而且可读的变量名
差
ymdstr = datetime.date.today().strftime("%y-%m-%d")
鬼知道 ymd 是什么?
好
current_date: str = datetime.date.today().strftime("%y-%m-%d")
看到 current_date, 一眼就懂.
2, 同类型的变量使用相同的词汇
差: 这三个函数都是和用户相关的信息, 却使用了三个名字
- get_user_info()
- get_client_data()
- get_customer_record()
好: 如果实体相同, 你应该统一名字
- get_user_info()
- get_user_data()
- get_user_record()
极好: 因为 Python 是一门面向对象的语言, 用一个类来实现更加合理, 分别用实例属性, property 方法和实例方法来表示.
- class User:
- info : str
- @property
- def data(self) -> dict:
- # ...
- def get_record(self) -> Union[Record, None]:
- # ...
3, 使用可搜索的名字
大部分时间你都是在读代码而不是写代码, 所以我们写的代码可读且可被搜索尤为重要, 一个没有名字的变量无法帮助我们理解程序, 也伤害了读者, 记住: 确保可搜索.
差
time.sleep(86400);
What the fuck, 上帝也不知道 86400 是个什么概念
好
- # 在全局命名空间声明变量, 一天有多少秒
- SECONDS_IN_A_DAY = 60 * 60 * 24
- time.sleep(SECONDS_IN_A_DAY)
清晰多了.
4, 使用可自我描述的变量
差
- address = 'One Infinite Loop, Cupertino 95014'
- city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'
- matches = re.match(city_zip_code_regex, address)
- save_city_zip_code(matches[1], matches[2])
matches[1] 没有自我解释自己是谁的作用
一般
- address = 'One Infinite Loop, Cupertino 95014'
- city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'
- matches = re.match(city_zip_code_regex, address)
- city, zip_code = matches.groups()
- save_city_zip_code(city, zip_code)
你应该看懂了, matches.groups() 自动解包成两个变量, 分别是 city,zip_code
好
- address = 'One Infinite Loop, Cupertino 95014'
- city_zip_code_regex = r'^[^,\\]+[,\\\s]+(?P<city>.+?)\s*(?P<zip_code>\d{5})?$'
- matches = re.match(city_zip_code_regex, address)
- save_city_zip_code(matches['city'], matches['zip_code'])
5, 不要强迫读者猜测变量的意义, 明了胜于晦涩
差
- seq = ('Austin', 'New York', 'San Francisco')
- for item in seq:
- do_stuff()
- do_some_other_stuff()
- # ...
- # Wait, what's `item` for again?
- dispatch(item)
seq 是什么? 序列? 什么序列呢? 没人知道, 只能继续往下看才知道.
好
- locations = ('Austin', 'New York', 'San Francisco')
- for location in locations:
- do_stuff()
- do_some_other_stuff()
- # ...
- dispatch(location)
用 locations 表示, 一看就知道这是几个地区组成的元组
6, 不要添加无谓的上下文
如果你的类名已经可以告诉了你什么, 就不要在重复对变量名进行描述
差
- class Car:
- car_make: str
- car_model: str
- car_color: str
感觉画蛇添足, 如无必要, 勿增实体.
好
- class Car:
- make: str
- model: str
- color: str
使用默认参数代替短路运算和条件运算
差:
- def create_micro_brewery(name):
- name = "Hipster Brew Co." if name is None else name
- slug = hashlib.sha1(name.encode()).hexdigest()
- # etc.
好
- def create_micro_brewery(name: str = "Hipster Brew Co."):
- slug = hashlib.sha1(name.encode()).hexdigest()
- # etc.
这个应该能理解吧, 既然函数里面需要对没有参数的变量做处理, 为啥不在定义的时候指定它呢?
--- EOF ---
任何问题可以扫描二维码给我留言
关注公众号「Python 之禅」, 回复「1024」免费获取 Python 资源
来源: http://www.tuicool.com/articles/zMnU3av