首页 > 解决方案 > 将两个相似的功能重构为一个?

问题描述

我有这个非常简单的注册/登录程序用于学习目的,它可以工作。但感觉就像我有重复的代码。必须明显的是检查功能。

我的问题是,我应该重构这两个以使它们合而为一,还是将它们分开更好?

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")

标签: pythonpython-3.x

解决方案


函数checkUser正在检查用户名是否已存在于 csv 文件中。这将在注册时发生。该功能checkPassword在用户登录时使用。这些功能应该保持独立,因为它们在不同级别的安全问题下做截然不同的事情。他们还期望根据用户在注册/登录过程中的位置进行输入。这意味着当您编写一个既喜欢又喜欢的doBoth(username, password)函数时,当您想在应用程序的注册时使用它时,您必须使用 null 调用此函数,doBoth(username, null)因为在注册时永远不知道密码。


推荐阅读