介绍

当我是新人的时候,当我收到前辈的代码审查时,我经常听到,
“嗯,我会这样写,但也没有错。”

起初,我并没有真正了解它的价值,所以我很不情愿地修复了它。
现在,我想我理解前辈的心情了,“我想告诉你细节”。

前辈指出的几点(Python例子)

单引号或双引号

  • 我自己
print('I'll be back')
  • 前辈
print("I'll be back")

为了写作而不逃避。

方法名称可以很长

  • 我自己
def check_file(self, file_name: str) -> bool:
    # check if a file exists
  • 前辈
def check_if_file_exists(self, file_name: str) -> bool:

能够从方法名称中读取功能(比注释更好)。

不要一遍又一遍地写同一个过程

  • 我自己
def func1(self):
    if cond1:
        do_something1()
    else:
        do_something2()

def func2(self):
    if cond1:
        do_something1()
    else:
        do_something2()
  • 前辈
def common_process(self):
    if cond1:
        do_something1()
    else:
        do_something2()

def func1(self):
    common_process()

def func2(self):
    common_process()

对于同一进程,增加了一种新方法来提高可读性和可维护性。

检查值是否在指定范围内

  • 我自己
if val > 0 and val < 100:
    do_something1()
if val < 0 or val > 100:
    do_something2()
  • 前辈
if 0 < val and val < 100:
    do_something1()
if val < 0 or 100 < val:
    do_something2()

是不是很容易理解,因为它类似于数学中的区间符号(0, 100)

不要创建额外的变量

  • 我自己
def get_basic_info(self, student: dict) -> dict:
    name = student.name
    age = student.age
    birth = student.birth
    basic_info = {
        "name": name,
        "age": age,
        "birth": birth
    }
    return basic_info
  • 前辈
def get_basic_info(self, student: dict) -> dict:
    basic_info = {
        "name": student.name,
        "age": student.age,
        "birth": student.birth,
    }
    return basic_info

浪费变量,冗长的程序。
字典末尾留逗号即可(方便加键或更改顺序时)

同时检查无和空字符串

  • 我自己
if val is not None and val != "":
    do_something()
  • 前辈
if not val:
    do_something()

一个not 就足够了。

先处理异常系统并返回

  • 我自己
if cond1:
    if cond2:
        do_something()
  • 前辈
if not cond1:
    return
if not cond2:
    return
do_something()

消除了深度缩进,逻辑简单。

不要在 bool 类型处理中创建不必要的分支

  • 我自己
def is_correct_answer(self) -> bool:
    if cond1:
        return True
    else:
        return False
  • 前辈
def is_correct_answer(self) -> bool:
    return cond1

我想在一行中做些什么。

长期条件的新变量

  • 我自己
if long_long_long_long_long_cond1 and long_long_long_long_long_cond2:
    do_something()
  • 前辈
cond1 = long_long_long_long_long_cond1
cond2 = long_long_long_long_long_cond2
if cond1 and cond2:
    do_something()

列出长条件会降低可读性。
如果变量名有某种意义就更好了。

如果你想传播列表

  • 我自己
age_list = [20, 21, 22]
age1 = age_list[0]
age2 = age_list[1]
age3 = age_list[2]
  • 前辈
age_list = [20, 21, 22]
age1, age2, age3 = age_list

元组也可以解包。

从字典中获取指定键的值

  • 我自己
if "name" in student_dict:
    name = student_dict["name"]
else:
    name = ""
  • 前辈
name = student_dict.get("name", "")

一排解决​​了密钥的存在性检查。

文件操作是上下文管理器(with语句)

  • 我自己
try:
    f = open("test.txt", "r")
except Exception as e:
    ... ...
else:
    data = f.read()
    f.close()
  • 前辈
with open("test.txt", "r") as f:
    data = f.read()

with 语句一直执行到关闭。

我想要一个临时工作目录

  • 我自己
import os
import shutil

temp_dir = "temporary_dir"
os.makedirs(temp_dir, exist_ok=True)  # ディレクトリを作成
do_something()
shutil.rmtree(temp_dir)  # ディレクトリを削除
  • 前辈
import os
import tempfile

with tempfile.TemporaryDirectory() as temp_dir:
    do_something()

它甚至会删除目录。

我想检查父类的类型

class Parent:
    pass

class Child(Parent):
    pass

item = Child()
  • 我自己
if type(item) is Child or type(item) is Parent:
    do_something()
  • 前辈
if isinstance(item, Parent):
    do_something()

type() 只检查实例的直接类,
可以检查isinstance(),包括继承源。

综上所述

这是一个过于详细而无法传达的代码审查。
我觉得有更好的写法,请参考。


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308632438.html

相关文章:

  • 2022-01-06
  • 2022-12-23
  • 2021-10-30
猜你喜欢
  • 2022-12-23
  • 2021-10-17
  • 2022-12-23
  • 2022-12-23
  • 2022-03-01
  • 2021-08-13
  • 2021-07-15
相关资源
相似解决方案