Wrong Suggested requires: Contract.Requires(System.Linq.Enumerable.Count(data) > 0);

Discussion Wrong Suggested requires: Contract.Requires(System.Linq.Enumerable.Count(data) > 0);

  • Monday, April 16, 2012 5:28 AM
     
      Has Code

    Consider the following code:

            private static void ProcessFirst(IEnumerable<int> data)
            {
                Contract.Requires(data != null);
                Contract.Requires(data.Any());
    
                var first = data.First();
                Console.WriteLine(first);
            }

    The static checker suggests

    CodeContracts: Suggested requires: Contract.Requires(System.Linq.Enumerable.Count(data) > 0)

    I think this is correct suggestion, if there is no Contract.Requires(data.Any()); present.

    I suggest to change static checker to use Any() because:

    1. Any() method is more efficient (enumerates only first element of sequence, while Count enumerates all elements)
    2. Any() is more human readable
    3. Resharper agreed with me about Any (it suggests to change Count() -> Any() too )

     PS: I have latest CodeContacts 1.4.50327.0




    • Edited by maxsur Monday, April 16, 2012 7:11 AM
    •  

All Replies

  • Friday, April 20, 2012 5:10 PM
    Owner
     
     

    thanks for the suggestion.

    We updated it, and now it will suggest Any

    ciao

    f

  • Friday, April 20, 2012 8:34 PM
     
     

    Thank you very much!

    Waiting for release with impatience.

    Finally we will get clear build output!

  • Wednesday, December 12, 2012 12:46 PM
     
     

    Hi Francesco,

    Could you or one of the other CodeContracts team please specify which version you expect this issue to be rectified by?

    I'm looking forward to resolving the same issue on some of my projects, but even when using the currently latest version (1.4.51019.0, which was released after your comment indicating the issue was fixed), CodeContracts still hints at using the Enumerable.Count() > 0 version of the condition.

  • Thursday, December 13, 2012 7:04 AM
     
     

    Hi Rob,

    Static checker is still suggests Count() > 0, but when you add contract with Any() this suggestion is dissapeared.

    Works at all my projects.

  • Thursday, December 13, 2012 10:15 AM
     
     

    Hi m.surikov,

    I'll give it another go, but I don't remember having that experience with CC. If the Contract.Requires() was defined in a functionally-equivalent but different format to the suggested version, the Static Checker simply made the same suggestion again.