Search code examples
c#dry

A "dry" principle case


there is a need to check the data entered by the user and display a notification on the screen in case of incorrect input. I used the following method, but it seems to me that it don't quite fit into the principle of "don't repeat yourself". Does anyone have any ideas for simplification?

int productid = 0;
string errorMessage = "Неправильный формат данных:\n",
       productName = "", productGroup = "", productType = "";
if (!int.TryParse(ProductIdTB.Text, out productId))
{
    errorMessage += "+ Номер продукта\n";
}
if (string.IsNullOrEmpty(ProductNameTB.Text))
{
    errorMessage += "+ Название продукта\n";
}
else
{
    productName = ProductNameTB.Text;
}
if (string.IsNullOrEmpty(ProductGroupTB.Text))
{
    errorMessage += "+ Группа продукта\n";
}
else
{
    productGroup = ProductGroupTB.Text;
}
if (string.IsNullOrEmpty(ProductType.Text))
{
    errorMessage += "+ Вид продукта";
}
else
{
    productType = ProductType.Text;
}
if (errorMessage.Split(' ').Length > 1)
{
    MessageBox.Show(errorMessage);
    return;
}

Solution

  • I can imagine building a class that does the checks for you and collects all errors, either in a string or a list of strings.

    class ErrorMessageBuilder
    {
        string totalmessage = "";
    
        void AppendErrorIfEmpty(TextBox t, string textboxname)
        {
            if (t.Text.IsNullOrEmpty())
            {
                totalmessage += textboxname + " can't be empty" + Environment.NewLine;
            }    
        }
    
        void AppendErrorIfNotInt(TextBox t, string textboxname)
        {
             int value;
             if (!int.TryParse(t.Text, out value))
             {
                 totalmessage += textboxname + " must be an integer number"  + Environment.NewLine;
             }
        }
    }
    

    This would reduce the code to

    var emb = ErrorMessageBuilder();
    emb.AppendErrorIfNotInt(ProductIdTB, "Product ID");
    emb.AppendErrorIfEmpty(ProductNameTB, "Product Name");
    ...
    

    Since this looks like WinForms development to me, you can also have a look at the ErrorProvider class. Like with tooltips, it allows one error message per control. Perhaps that would be even more user-friendly.