需要重构建议/想法

发布于 2024-08-17 11:15:31 字数 1634 浏览 1 评论 0原文

我正在寻找改进以下代码的想法

static void Main(string[] args)
{
    bool validInput1 = false;
    string input1 = string.Empty;
    bool validInput2 = false;
    string input2 = string.Empty;

    bool validFilePath = false;
    string filePath = string.Empty;


    try
    {
        Console.WriteLine("Import process started.");

        while (!validFilePath)
        {
            Console.Write("Please enter the full path to the file you would like to import: ");
            filePath = Console.ReadLine().Replace("\"","");
            if (File.Exists(filePath))
                validFilePath = true;
        }

        while (!validInput1)
        {
            Console.Write("Enter a valid eventID the import file: ");
            input1 = Console.ReadLine();
            if (ValidEventID(input1.Trim().Length))
                validInput1 = true;
        }

        while (!validInput2)
        {
            Console.Write("Enter a valid import type code: ");
            input2 = Console.ReadLine();
            if (input2.Trim().ToUpper() == "EX" || input2.Trim().ToUpper() == "EL")
                validInput2 = true;
        }


        var records = Utilities.ParseCSV(filePath);
        var import = new Import
        {
            EventId = input1,
            ImportType = input2
        };


        import.ImportEventDates(records);

        Console.WriteLine("Import process completed.");
        Console.ReadLine();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error encountered");
        Console.WriteLine(ex.ToString());
        Console.ReadLine();
    }
}

提前感谢您的帮助

I was looking for ideas on improving the following code

static void Main(string[] args)
{
    bool validInput1 = false;
    string input1 = string.Empty;
    bool validInput2 = false;
    string input2 = string.Empty;

    bool validFilePath = false;
    string filePath = string.Empty;


    try
    {
        Console.WriteLine("Import process started.");

        while (!validFilePath)
        {
            Console.Write("Please enter the full path to the file you would like to import: ");
            filePath = Console.ReadLine().Replace("\"","");
            if (File.Exists(filePath))
                validFilePath = true;
        }

        while (!validInput1)
        {
            Console.Write("Enter a valid eventID the import file: ");
            input1 = Console.ReadLine();
            if (ValidEventID(input1.Trim().Length))
                validInput1 = true;
        }

        while (!validInput2)
        {
            Console.Write("Enter a valid import type code: ");
            input2 = Console.ReadLine();
            if (input2.Trim().ToUpper() == "EX" || input2.Trim().ToUpper() == "EL")
                validInput2 = true;
        }


        var records = Utilities.ParseCSV(filePath);
        var import = new Import
        {
            EventId = input1,
            ImportType = input2
        };


        import.ImportEventDates(records);

        Console.WriteLine("Import process completed.");
        Console.ReadLine();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error encountered");
        Console.WriteLine(ex.ToString());
        Console.ReadLine();
    }
}

Thanks in advance for any help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤檠 2024-08-24 11:15:31

我会编写一个简单的方法来检索和验证用户输入:

public static string PromptUntilValid(string promptText, Func<string, bool> validationPredicate)
{
    string input;
    do
    {
        Console.Write(promptText);
        input = Console.ReadLine();
    } while (!validationPredicate(input))
    return input;
}

这将允许您的代码重构如下:

    ...

    filePath = PromptUntilValid(
        "Please enter the full path to the file you would like to import: ",
        s => File.Exists(s));

    input1 = PromptUntilValid(
        "Enter a valid eventID the import file: ",
        s => ValidEventID(s.Trim().Length));

    input2 = PromptUntilValid(
        "Enter a valid import type code: ",
        s => s.Trim().ToUpper() == "EX" || s.Trim().ToUpper() == "EL");

    ...

I'd write a simple method to retrieve and validate user input :

public static string PromptUntilValid(string promptText, Func<string, bool> validationPredicate)
{
    string input;
    do
    {
        Console.Write(promptText);
        input = Console.ReadLine();
    } while (!validationPredicate(input))
    return input;
}

This would allow your code to be refactored as follows :

    ...

    filePath = PromptUntilValid(
        "Please enter the full path to the file you would like to import: ",
        s => File.Exists(s));

    input1 = PromptUntilValid(
        "Enter a valid eventID the import file: ",
        s => ValidEventID(s.Trim().Length));

    input2 = PromptUntilValid(
        "Enter a valid import type code: ",
        s => s.Trim().ToUpper() == "EX" || s.Trim().ToUpper() == "EL");

    ...
在巴黎塔顶看东京樱花 2024-08-24 11:15:31

您可以尝试取出 while 循环并将它们放入各自的函数中,这些函数返回有效的文件路径和输入,并在捕获异常时抛出异常。例如:

public string FindValidFilepath()
{
    string filePath = string.Empty
    try{
        while (!validFilePath)
        {
            Console.Write("Please enter the full path to the file you would like to import: ");
            filePath = Console.ReadLine().Replace("\"","");
            if (File.Exists(filePath))
                validFilePath = true;
        }
    } catch (Exception ex) {
        throw;
    }
    return filePath
}

并从 Main 函数中调用它。如果必须添加代码,您可以做的其他事情可以减少错误,即在 If 语句中的代码周围放置大括号 {。虽然没有它们在语法上是合法的,但它可以防止以后出现错误。我过去也曾被这样的错误所困扰。

编辑:重新抛出此异常是为了使原始的 Try-Catch 块可以保留在原处。另外,我了解到“throw ex”会丢失堆栈跟踪,但简单地“throw”会保留它。我已经纠正了这个问题。

编辑2:我想到的另一件事是,尝试捕获特定的异常并输出特定的错误,向用户解释出了什么问题,以便他们可以更好地理解问题。大多数用户不理解堆栈跟踪,除非需要输出堆栈跟踪。

另外,请原谅任何小的语法错误,我对 Java 比 C# 更熟悉。

You could try taking the while loops out and putting them each in their own functions which return the valid filepath and inputs and throw exceptions if they're caught. For example:

public string FindValidFilepath()
{
    string filePath = string.Empty
    try{
        while (!validFilePath)
        {
            Console.Write("Please enter the full path to the file you would like to import: ");
            filePath = Console.ReadLine().Replace("\"","");
            if (File.Exists(filePath))
                validFilePath = true;
        }
    } catch (Exception ex) {
        throw;
    }
    return filePath
}

and call it from the Main function. Other things you can do which will reduce errors if you have to add code is to put curly braces, {, around the code within your If statements. While not having them is syntactically legal, it will keep an error from popping up later. I have been bitten by a mistake like that in the past.

EDIT: The rethrowing of this exception is so that the original Try-Catch block can stay in place. Also, I've learned that "throw ex" loses the stack trace but simply "throw" keeps it. I've corrected this issue.

EDIT 2: One more thing I thought of, try catching specific exceptions and outputting a specific error explaining what went wrong to the user so they can better understand the problem. Most users don't understand a stack trace unless outputting the stack trace is a requirement.

Also, please excuse any small syntax errors, I'm more familiar with Java than C#.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文