Search code examples
ndepend

query to detect ISP violations


I am trying to create a special query with NDepend, but cannot figure it out.

Here's what I'd like to query in a more procedural pseudocode:

var list
foreach type t
    foreach i = t.attribute that is an interface
        var nm = i.numberOfMethods
        var mu = numberOfMethods that t actually uses
        if mu / nm < 1
        list.Add(t)
    end foreach
end foreach
return list

It's supposed to list types that don't comply with the Interface Segregation Principle.

Thanks!


Solution

  • So the query you ask can be written this way:

    from t in JustMyCode.Types where !t.IsAbstract
    
    from i in t.TypesUsed where i.IsInterface
    
    // Here collect methods of i that are not used
    let methodsOfInterfaceUnused = i.Methods.Where(m => !m.IsUsedBy(t))
    where methodsOfInterfaceUnused.Count() > 0
    select new { t, methodsOfInterfaceUnused }
    

    This query has the peculiarity to match several time a same type, one for each time methodsOfInterfaceUnused is not empty. The result is then nicely presented and understandable:

    Segregation Principle with NDepend