【问题标题】:Can CQL be used to find methods that return `null`?可以使用 CQL 查找返回“null”的方法吗?
【发布时间】:2015-10-07 08:23:36
【问题描述】:

我想找出所有可以显式返回 null 的方法。

在 NDepend 中是否可以使用 CQL?

【问题讨论】:

    标签: cql ndepend


    【解决方案1】:

    目前不知道,CQL 到目前为止还不知道变量的值、字段和返回的值。

    但是,建议使用以下默认规则。这个想法是,如果一个方法返回一个引用,它永远不应该为空,并且应该添加一个合约来断言它。如果您希望这样的方法返回 null,请改用 Try... 模式,例如 TryParse(string s, out T val):bool

    // <Name>Public methods returning a reference needs a contract to ensure that a non-null reference is returned</Name>
    warnif count > 0
    let ensureMethods = Application.Methods.WithFullName(
       "System.Diagnostics.Contracts.__ContractsRuntime.Ensures(Boolean,String,String)")
    
    from ensureMethod in ensureMethods
    from m in ensureMethod.ParentAssembly.ChildMethods where 
      m.IsPubliclyVisible &&
     !m.IsAbstract &&
      m.ReturnType != null &&
      // Identify that the return type is a reference type
      (m.ReturnType.IsClass || m.ReturnType.IsInterface) &&
     !m.IsUsing(ensureMethod) &&
    
      // Don't match method not implemented yet!
     !m.CreateA("System.NotImplementedException".AllowNoMatch())
    
    select new { 
       m, 
       ReturnTypeReference = m.ReturnType 
    }
    
    //<Description>
    // **Code Contracts** are useful to decrease ambiguity between callers and callees.
    // Not ensuring that a reference returned by a method is *non-null* leaves ambiguity 
    // for the caller. This rule matches methods returning an instance of a reference type 
    // (class or interface) that don't use a **Contract.Ensure()** method.
    //
    // *Contract.Ensure()* is defined in the **Microsoft Code Contracts for .NET** 
    // library, and is typically used to write a code contract on returned reference:
    // *Contract.Ensures(Contract.Result<ReturnType>() != null, "returned reference is not null");*
    // https://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970
    //</Description>
    
    //<HowToFix>
    // Use *Microsoft Code Contracts for .NET* on the public surface of your API,
    // to remove most ambiguity presented to your client. Most of such ambiguities
    // are about *null* or *not null* references.
    //
    // Don't use *null* reference if you need to express that a method might not 
    // return a result. Use instead the **TryXXX()** pattern exposed for example 
    // in the *System.Int32.TryParse()* method.
    //</HowToFix>
    

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2012-06-22
      • 2012-07-06
      • 2016-10-17
      • 2010-11-10
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多