程序鲁棒性问题

1 参数有效性检查

  编写业务逻辑时,从鲁棒性的角度出发,需要对方法的参数进行有效性检查,比如空值检查、空字符串检查、字符串长度检查、范围检查等。

using System;

namespace ConsoleApp1
{
    /// <summary>
    /// Guard类有两个静态方法,分别对空对象和空字符进行判断(静态方法不需要实例化即可调用)。
    /// </summary>
    class Guard
    {
        public static void NotNull(object param, string paramName)
        {
            if (param is null)
            {
                ArgumentNullException argNullException = new ArgumentNullException(paramName);
                throw new Exception(String.Format("Parameter '{0}' cannot be null!", paramName), argNullException);
                //throw new ArgumentNullException(paramName);
            }
        }
        public static void NotNullorEmpty(string param, string paramName)
        {
            NotNull(param, paramName);
            if (param == string.Empty)
            {
                ArgumentException argException = new ArgumentException(paramName);
                throw new Exception(String.Format("String '{0}' cannot be empty!", paramName), argException);
                //throw new ArgumentException($"The string cannot be empty.", paramName);
            }
        }
    }
    
    /// <summary>
    /// Test类用于测试Guard类,或者说,Test类展示了Guard类的使用方法。
    /// </summary>
    class Test
    {
        Guard guard;
        public Test()
        {
            this.guard = new Guard();
        }

        public void TestNotNull(string str)
        {
            Guard.NotNull(str, nameof(str));
        }
        public void TestNotNullorEmpty(string str)
        {
            Guard.NotNullorEmpty(str, nameof(str));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            //test.TestNotNull(null);
            string tmp = string.Empty;
            test.TestNotNullorEmpty(tmp);
        }
    }
}

2 可操作性

  编程的时候,任何可能会出错的操作,都要try…catch…一下,比如往串口写数据。

参考链接
1.C# 9.0 新特性之参数非空检查简化
2.C#检验参数合法性公用方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值