vendredi 12 avril 2019

Conditional optimization/readability

I currently have a controller that is reading a text file, checking the data, and then outputting to the view. I was wondering if there may be a better way to accomplish my check?

Here is where I read my file, and do my checks. As you can see my check is pretty long and after I add 3 or 4 more if else conditionals, it may end up unreadable if it isn't already. Any suggestions would be appreciated!

                using (var sr = new StreamReader(newFullPath))
                {
                    while ((strbuild = sr.ReadLine()) != null)
                    {
                        var strArray = strbuild.Split('|');
                        string INum = string.Empty,
                            IDate = string.Empty,
                            site = string.Empty,
                            PG = string.Empty,
                            errors = string.Empty;

                        if (strArray[0] == "1")
                        {
                            FileCheck(strArray, out INum, out IDate, out site, out PG, out errors);
                            var model = new UploadFileValidation
                            {
                                InvoiceNumber = INum,
                                Errors = errors
                            };
                            validateOutput.Add(model);
                        }
                    }

                    return View(validateOutput);
                }

The check is below

    private void FileCheck(string[] strArray, out string INum, out string IDate, out string site, out string PG, out string errors)
    {
        INum = strArray[1];
        IDate = strArray[2];
        errors = "";
        site = strArray[10];
        var check = strArray.ElementAtOrDefault(11) != null;
        if (check)
            PG = strArray[11];
        else
            PG = "";
        string[] errorformats = { $"Unsupported date format of {IDate}.", "Site is missing", "Invalid Pay group" };
        string[] format = { "MM/dd/yyyy", "M/dd/yyyy", "MM/d/yyyy", "M/d/yyyy" };
        DateTime dateTime;
        if (!DateTime.TryParseExact(IDate, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
            errors = $"{errorformats[0]}";
        if (PG == "" && errors != "")
            errors = $"{errors}<br>{errorformats[2]}";
        else if (PG == "" && errors == "")
            errors = $"{errors}<br>{errorformats[1]}";
        if (site == "" && errors != "")
            errors = $"{errors}<br>{errorformats[1]}";
        else if (site == "" && errors == "")
            errors = $"{errorformats[1]}";
    }

Here is the end result Example

Aucun commentaire:

Enregistrer un commentaire