使用自定义卫语句写出更简洁的代码

前言

上次,我们介绍了Pitcher,可以帮我们简化卫语句:

public User(string name, int age)
{
    Throw.When(string.IsNullOrWhiteSpace(name), new ArgumentNullException(nameof(name)));
    Throw.When(age <= 0, new ArgumentOutOfRangeException(nameof(age)));

    //正常业务逻辑
    this.Name = name; 
    this.Age = age; 
}

但是,这样的代码还是不够简洁,因为我们更关注正常业务逻辑。

Ardalis.GuardClauses

今天,我们介绍另一个Nuget包Ardalis.GuardClauses来实现卫语句。

Ardalis.GuardClauses提供了Guard.Against对象,基本API如下:

  • Guard.Against.Null 判断是否为null

  • Guard.Against.NullOrEmpty 判断是否为null或空

  • Guard.Against.NullOrWhiteSpace 判断是否为null或空或空格

  • Guard.Against.OutOfRange 判断是否超出范围

相对于Pitcher,它的优势在于,每个卫语句都有返回值,前面的代码可以改成这样:

public User(string name, int age)
{
    this.Name = Guard.Against.NullOrWhiteSpace(name, nameof(name));
    this.Age = Guard.Against.OutOfRange(age, nameof(age), 1, 100);
}

自定义卫语句

除此之外,对于特殊条件的卫语句,我们可以使用Guard.Against对象编写扩展方法,让语义更清晰:

namespace Ardalis.GuardClauses
{
    public static class UserGuard
    {
        public static int InvalidAge(this IGuardClause guardClause, int age)
        {
            var validAges = new[] { 1, 3, 5 };
            if (!validAges.Contains(age))
                throw new Exception("年龄不符");

            return age;
        }
    }
}

public User(string name, int age)
{
    this.Name = Guard.Against.NullOrWhiteSpace(name, nameof(name));
    this.Age = Guard.Against.InvalidAge(age);
}

结论

使用Ardalis.GuardClauses,可以让卫语句更简洁易读。

如果你觉得这篇文章对你有所启发,请关注我的个人公众号”My IO“

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值