python - 将两个相似的功能重构为一个?
问题描述
我有这个非常简单的注册/登录程序用于学习目的,它可以工作。但感觉就像我有重复的代码。必须明显的是检查功能。
我的问题是,我应该重构这两个以使它们合而为一,还是将它们分开更好?
def signUp():
username = input("Give me a username: ")
if checkUser(username) == True:
print("You are already registrered, please log in with your password.")
else:
password = input("Also give me a password: ")
with open("sign-up.csv", "a", newline="") as file:
writer = csv.writer(
file, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL
)
writer.writerow([username, password])
print("You are now signed up. Please log in with your credentials.")
def logIn():
username = input("Give me your username: ")
password = input("Also give me your password: ")
if checkPassword(username, password) == True:
print("Welcome, you are now logged in.")
else:
print("Username or password is incorrect please try again.")
def checkUser(username):
with open("sign-up.csv", "r") as file:
reader = csv.reader(file)
myList = dict(reader)
if username in myList:
return True
else:
return False
def checkPassword(username, password):
with open("sign-up.csv", "r") as file:
reader = csv.reader(file)
myList = dict(reader)
if username in myList and password == myList[username]:
return True
else:
return False
def get_user_choice():
print("\n[1] Sign up")
print("[2] Log in")
print("[q] Quit")
return input("What would you like to do? ")
choice = ""
while choice != "q":
choice = get_user_choice()
if choice == "1":
signUp()
elif choice == "2":
logIn()
elif choice == "q":
print("Welcome back some other day")
else:
print("That choice doesn't exists")
解决方案
函数checkUser
正在检查用户名是否已存在于 csv 文件中。这将在注册时发生。该功能checkPassword
在用户登录时使用。这些功能应该保持独立,因为它们在不同级别的安全问题下做截然不同的事情。他们还期望根据用户在注册/登录过程中的位置进行输入。这意味着当您编写一个既喜欢又喜欢的doBoth(username, password)
函数时,当您想在应用程序的注册时使用它时,您必须使用 null 调用此函数,doBoth(username, null)
因为在注册时永远不知道密码。
推荐阅读
- jquery - kendo-ui 数据源有数据,但视图为空
- user-interface - Unity EditorGUILayout IntSlider 不起作用
- swift - SwiftUI = ObservableObject 作为类的选择
- android - 数据绑定返回 null
- php - 自定义请求的中间件
- mysql - 对于每个号码,查找仅使用该号码发布的广告
- python - 如何让 Python3.7 指向另一个 Python 解释器
- xml - 无法将值“System.Object[]”转换为类型“System.Xml.XmlDocument”。错误:“'&' 是一个意外的标记。预期的标记是 ';'
- javascript - 如何从 FileReader.readAsText 恢复原始 blob?
- python - 如何在海龟中制作出与填充颜色不同的线条颜色