You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于DRY原则简化用户输入校验与错误提示代码?

简化表单校验代码(遵循DRY原则)

你当前的代码存在大量重复的校验逻辑,以下是几种简化思路和实现方式:

原代码

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;
}

简化方案1:封装通用校验方法

把重复的空值校验逻辑封装成方法,类型校验单独处理,减少代码重复:

int productId = 0;
string productName = "", productGroup = "", productType = "";
List<string> errors = new List<string>();

// 校验产品编号(整数类型)
if (!int.TryParse(ProductIdTB.Text, out productId))
{
    errors.Add("Номер продукта");
}

// 封装空值校验+赋值的通用方法
bool ValidateNotEmpty(TextBox input, out string result, string errorMsg)
{
    result = input.Text;
    if (string.IsNullOrEmpty(result))
    {
        errors.Add(errorMsg);
        return false;
    }
    return true;
}

// 调用方法完成校验与赋值
ValidateNotEmpty(ProductNameTB, out productName, "Название продукта");
ValidateNotEmpty(ProductGroupTB, out productGroup, "Группа продукта");
ValidateNotEmpty(ProductType, out productType, "Вид продукта");

// 输出错误信息
if (errors.Count > 0)
{
    string errorMessage = $"Неправильный формат данных:\n{string.Join("\n+ ", errors)}";
    MessageBox.Show(errorMessage);
    return;
}

简化方案2:批量处理校验项

用集合存储所有校验项的信息,通过循环统一处理,后续新增校验项只需追加条目,扩展性更强:

int productId = 0;
string productName = "", productGroup = "", productType = "";
List<string> errors = new List<string>();

// 定义校验项集合,包含输入控件、错误提示、处理逻辑
var validationItems = new List<(TextBox Input, string ErrorMsg, Action<string> Handler)>
{
    (ProductIdTB, "Номер продукта", text => 
    {
        if (!int.TryParse(text, out productId)) errors.Add("Номер продукта");
    }),
    (ProductNameTB, "Название продукта", text => 
    {
        if (string.IsNullOrEmpty(text)) errors.Add("Название продукта");
        else productName = text;
    }),
    (ProductGroupTB, "Группа продукта", text => 
    {
        if (string.IsNullOrEmpty(text)) errors.Add("Группа продукта");
        else productGroup = text;
    }),
    (ProductType, "Вид продукта", text => 
    {
        if (string.IsNullOrEmpty(text)) errors.Add("Вид продукта");
        else productType = text;
    })
};

// 循环处理所有校验项
foreach (var item in validationItems)
{
    item.Handler(item.Input.Text);
}

// 输出错误信息
if (errors.Count > 0)
{
    string errorMessage = $"Неправильный формат данных:\n{string.Join("\n+ ", errors)}";
    MessageBox.Show(errorMessage);
    return;
}

核心优化点

  • 用List<string>收集错误信息,替代字符串拼接,避免冗余的错误判断逻辑
  • 封装或批量处理后,重复的if-else逻辑被消除,新增校验项只需添加对应配置或方法调用
  • 统一错误信息的生成格式,避免手动拼接换行符的失误

内容的提问来源于stack exchange,提问作者programMUSTer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 11:37:12