i want find methods can explicitly return null.
is possible in ndepend using cql?
not now, cql far doesn't know value of variables, fields , values returned.
however default rule below proposed. idea if method returns reference should never null, , contract should added assert this. if wish such method return null, instead use try... pattern, in tryparse(string s, out t val):bool.
// <name>public methods returning reference needs contract ensure non-null reference returned</name> warnif count > 0 let ensuremethods = application.methods.withfullname( "system.diagnostics.contracts.__contractsruntime.ensures(boolean,string,string)") ensuremethod in ensuremethods m in ensuremethod.parentassembly.childmethods m.ispubliclyvisible && !m.isabstract && m.returntype != null && // identify return type 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** useful decrease ambiguity between callers , callees. // not ensuring reference returned method *non-null* leaves ambiguity // caller. rule matches methods returning instance of reference type // (class or interface) don't use **contract.ensure()** method. // // *contract.ensure()* defined in **microsoft code contracts .net** // library, , typically used write code contract on returned reference: // *contract.ensures(contract.result<returntype>() != null, "returned reference not null");* // https://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970 //</description> //<howtofix> // use *microsoft code contracts .net* on public surface of api, // remove ambiguity presented client. of such ambiguities // *null* or *not null* references. // // don't use *null* reference if need express method might not // return result. use instead **tryxxx()** pattern exposed example // in *system.int32.tryparse()* method. //</howtofix>
Comments
Post a Comment