在撸码过程中,总有很多代码需要重构,码一个问候用户的小例子,加深对代码重构的印象。

原始代码:

1 import json
 2 
 3 filename = 'username.json' #定义文件名
 4 
 5 try:
 6     with open(filename) as file_object:
 7         username = json.load(file_object) #加载存储的用户名,如果有的话
 8 
 9 except FileNotFoundError: 
10     username = input("what is your name: ")
11     with open(filename,'w') as file_object: #以写入的方式打开文件filename
12         json.dump(username,file_object) #将username写入到文件对象中
13         print("We will remember you when you back " +username + "!") #打印问候语
14 
15 else:
16     print("Welcome back, " + username + "!") #打印问候语

代码重构1,将代码全部封装到一个函数里面:

1 import json
 2 
 3 '''定义函数,用于代码封装'''
 4 def greet_user():
 5     filename = 'username.json'
 6     try:
 7         with open(filename) as file_object:
 8             username = json.load(file_object)
 9 
10     except FileNotFoundError:
11         username = input("What is your name: ")
12         with open(filename,'w') as file_object:
13             json.dump(username,file_object)
14             print("We will remember you when you back, " + username + "!")
15 
16     else:
17         print("Welcome back, " + username + "!")
18 
19 greet_user() #调用函数问候

代码重构2,将代码重构1的函数进一步拆分,让函数greet_user()不执行那么多任务,我们将获取存储的用户名的代码写到另一个get_stored_user()函数中。

1 import json
 2 
 3 
 4 def get_stored_user():
 5     filename = 'username.json'
 6     try:
 7         with open(filename) as file_object:
 8             username = json.load(file_object)
 9 
10     except FileNotFoundError:
11         return None
12 
13     else:
14         return username
15 
16 
17 def greet_user():
18     username = get_stored_user()
19     if username:
20         print("Welcome back " + username + "!")
21     else:
22         username = input("What is your name: ")
23         filename = 'username.json'
24         with open(filename,'w') as file_object:
25             json.dump(username,file_object)
26             print("We will remember you when you back, " + username + "!")
27  
28 greet_user() #调用函数问候

代码重构3,由于最终的目的是问候用户,我们可以将重构2里的代码进一步拆分,将没有用户名的时候提示输入用户名的代码存储在另外一个函数中。

1 import json
 2 
 3 def get_stored_user():
 4     '''定义函数以获取存储了的用户名'''
 5     filename = 'username.json'
 6     try:
 7         with open(filename) as file_object:
 8             username = json.load(file_object)
 9     except FileNotFoundError:
10         return None
11     else:
12         return username #返回用户名
13 
14 def get_new_user():
15     '''定义函数以获取用户输入'''
16     username = input("What is your name: ")
17     filename = 'username.json'
18     with open(filename,'w') as file_object:
19         json.dump(username,file_object)
20 
21     return username #返回用户名
22 
23 def greet_user():
24     '''定义函数问候用户'''
25     username = get_stored_user()
26     if username:
27         print("Welcome back, " + username + "!")
28     else:
29         username = get_new_user()
30         print("We will remember you when you back, " + username + "!")
31 
32 greet_user() #调用函数,打印问候语

代码重构的意义在于,简化同一个代码块的任务量,让代码更容易读懂。