CodeContracts和null检查详细程度

时间:2012-07-31 19:23:07

标签: c# generics nullreferenceexception code-contracts

我目前正在减少我在应用程序框架中的一些重复,我想知道人们对以下扩展方法的看法是什么?

[EditorBrowsable(EditorBrowsableState.Never)]
public static class ThrowExtensions
{
    public static T ThrowIfNull<T>(this T instance) where T : class
    {
        Contract.Ensures(Contract.Result<T>() != null);

        if (instance == null)
        {
            throw new ArgumentNullException("instance", string.Format("Object reference of type '{0}' not set to an instance of an object.", typeof(T).FullName));
        }

        return instance;
    }
}

请考虑以下示例。

我知道扩展一切都不是一个好习惯,如果可能我应该避免它,但在这种情况下,虽然不漂亮但看起来很合理。

protected bool Contains<TEntity>(TEntity entity) where TEntity : class
{
    Contract.Requires(entity != null);

    ObjectStateEntry entry;

    bool exist = ((IObjectContextAdapter)_context).ObjectContext.ThrowIfNull().ObjectStateManager.ThrowIfNull().TryGetObjectStateEntry(entity, out entry);

    return exist;
}

编辑:我也在考虑使用Try()更改ThrowIfNull或者更符合此上下文的内容作为框架中的约定,但我真的很喜欢它,如果你有一个更好的选择我很高兴听到它,谢谢!

更新:到目前为止,这就是我最终的结果。

namespace EasyFront.Framework.Diagnostics.Contracts
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics.Contracts;

    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class ContractsExtensions
    {
        /// <summary>
        ///     Calls the code wrapped by the delegate when the subject is not pointing to null, otherwise, <see
        ///      cref="ArgumentNullException" /> is thrown.
        /// </summary>
        /// <remarks>
        ///     Eyal Shilony, 01/08/2012.
        /// </remarks>
        /// <typeparam name="TSubject"> The type of the subject to operate on. </typeparam>
        /// <typeparam name="TResult"> The type of the result to return from the call. </typeparam>
        /// <param name="subject"> The subject to operate on. </param>
        /// <param name="func"> The function that should be invoked when the subject is not pointing to null. </param>
        /// <returns> The result of the invoked function. </returns>
        public static TResult SafeCall<TSubject, TResult>(this TSubject subject, Func<TSubject, TResult> func)
            where TSubject : class
        {
            Contract.Requires(func != null);

            if (subject == null)
            {
                ThrowArgumentNull<TSubject>();
            }

            return func(subject);
        }

        /// <summary>
        ///     Calls the code wrapped by the delegate when the subject is not pointing to null,
        ///     otherwise, <see cref="ArgumentNullException" /> is thrown.
        /// </summary>
        /// <remarks>
        ///     Eyal Shilony, 01/08/2012.
        /// </remarks>
        /// <typeparam name="TSubject"> The type of the subject to operate on. </typeparam>
        /// <param name="subject"> The subject to operate on. </param>
        /// <param name="func"> The function that should be invoked when the subject is not pointing to null. </param>
        public static void SafeCall<TSubject>(this TSubject subject, Action<TSubject> func)
            where TSubject : class
        {
            Contract.Requires(func != null);

            if (subject == null)
            {
                ThrowArgumentNull<TSubject>();
            }

            func(subject);
        }

        /// <summary>
        ///     Ensures that the subject is not pointing to null and returns it, otherwise, <see cref="ArgumentNullException" /> is thrown.
        /// </summary>
        /// <remarks>
        ///     Eyal Shilony, 01/08/2012.
        /// </remarks>
        /// <typeparam name="TSubject"> The type of the subject to operate on. </typeparam>
        /// <param name="subject"> The subject to operate on. </param>
        /// <returns> The subject. </returns>
        public static TSubject SafeReturn<TSubject>(this TSubject subject)
            where TSubject : class
        {
            Contract.Ensures(Contract.Result<TSubject>() != null);

            if (subject == null)
            {
                ThrowArgumentNull<TSubject>();
            }

            return subject;
        }

        private static void ThrowArgumentNull<TSubject>() where TSubject : class
        {
            // ReSharper disable NotResolvedInText
            throw new ArgumentNullException("subject", string.Format("Object reference of type '{0}' not set to an instance of an object.", typeof(TSubject).FullName));
            // ReSharper restore NotResolvedInText
        }
    }
}

以下列出了我编制的优缺点。

优点:

  • 删除复杂空检查的冗余。
  • 与NullReferenceException相比,提供有关错误的更多信息。
  • 集中放置,您可以在其中控制错误的行为,例如在生产版本中,您可以决定要使用异常,在调试版本中,您可以选择使用断言或记录传播的异常。
  • 代码可以更加可读和优雅。

缺点:

  • 性能?
  • 陡峭的学习曲线,特别适合那些对代表,lambda操作员或函数式编程感到不舒服的人。
  • 降低清晰度。

以下是我必须处理的一些代码。

var entity = Builder.Entity<User>();

entity.HasKey(u => u.Id);
entity.Property(u => u.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
entity.Property(u => u.DisplayName).IsRequired();
entity.Property(u => u.DisplayName).HasMaxLength(20);
entity.Property(u => u.Username).HasMaxLength(50);
entity.Property(u => u.Password).HasMaxLength(100);
entity.Property(u => u.Salt).HasMaxLength(100);
entity.Property(u => u.IP).HasMaxLength(20);
entity.Property(u => u.CreatingDate);
entity.Property(u => u.LastActivityDate);
entity.Property(u => u.LastLockoutDate);
entity.Property(u => u.LastLoginDate);
entity.Property(u => u.LastPasswordChangedDate);

1 个答案:

答案 0 :(得分:0)

Jeffrey的评论非常有价值,所以我只是忽略了使用ContractVerificationAttribute的警告。