I'm comparing two APIs to generate a method in C# and want to measure how "complex" the code to use them is. Consider:


MethodDeclaration(PredefinedType(Token(IntKeyword)), "CompareTo")


new CodeMemberMethod
    Attributes = Public | Final,
    ReturnType = new CodeTypeReference(typeof(int)),
    Name = "CompareTo",
    Parameters =
        new CodeParameterDeclarationExpression("Person", "other")

(If anyone's curious, API A is Roslyn SyntaxFactory, API B is CodeDOM.)

Notice how with API A, you have to care about things like tokens or identifiers, which in my opinion makes it more complex. But:

  • If we count the number of lines, API B is much worse (4 lines vs. 10 lines). But part of that is due to the indentation style I use, which is not really about difference between the APIs.
  • If we count the number of non-whitespace characters, API A is worse, but not by much (192 vs. 175). But in this metric, API B is hurt by its overlong names, which I think don't actually makes the code more complex.

So my question is: are there ways to measure this kind of code complexity, accepted in the industry or in academia? If not, is "number of non-whitespace characters" the best I can do?

Some other measures of complexity I rejected:

  • Cyclomatic complexity is not relevant here, since both cases are non-conditional expressions.
  • Kolmogorov complexity is a theoretical concept that can't actually be computed in practice. Maybe some kind of approximation of it could work?
  • 1
    How about asking your colleagues which they find easier to read and understand? Ask them to explain you what they are reading and see if that matches with what is intended. – Bart van Ingen Schenau Aug 3 '18 at 16:12
  • 1
    Are you trying to measure complexity as a proxy for usability? Having no experience with either of these, and just going by your two small examples API A looks like it has a much better UX for using. – Hangman4358 Aug 3 '18 at 16:20
  • A minor improvement is to substitute a count of tokens for characters. Increasing the length of a name doesn't increase complexity so the raw count of characters is counting the wrong thing. – JimmyJames Aug 3 '18 at 18:36
  • I favor latter as it feels more declarative. – Erik Eidt Aug 3 '18 at 18:39
  • 1
    It would be helpful if you could state the purpose of your proposed metric. Some things, like ease of use and readability, are inherently subjective. – Robert Harvey Aug 3 '18 at 19:07

Use a parser to examine the abstract syntax tree. The complexity is related to the number of nodes and leaves in that tree.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.