feO2x / Light.GuardClauses

A lightweight .NET library for expressive Guard Clauses.
MIT License
85 stars 8 forks source link

Add NoEnumerationAttribute to MustNotBeNull checks #82

Closed cdonnellytx closed 1 year ago

cdonnellytx commented 1 year ago

JetBrains annotations now includes a NoEnumerationAttribute:

Indicates that IEnumerable passed as a parameter is not enumerated. Use this annotation to suppress the 'Possible multiple enumeration of IEnumerable' inspection.

At a minimum I would like to add this to the MustNotBeNull and MustNotBeNullReference checks, as those check strictly against nulls.

I evaluated other methods as follows:

Method name Safe? Reason
MustNotBeNull Does identity check against null
MustNotBeNullReference Does identity check against null
IsSameAs Does identity check against two values
MustNotBeSameAs Does identity check against two values
MustNotBeDefault Calls Equals which can be overridden and in theory enumerate.
MustHaveValue HasValue, Value cannot be overridden and do not enumerate
MustBe Calls Equals which can be overridden and in theory enumerate.
MustNotBe Calls Equals which can be overridden and in theory enumerate.

Everything else either operates on a strictly non-enumerable type (e.g, MustBeEmpty(Guid)), on a "well-known" enumerable type that is not streaming (e.g. string), or an enumerable that may be streaming.

I have a branch I intend to submit as a PR if you are comfortable with these changes.

Thanks for making a great library!

# Chris

feO2x commented 1 year ago

Hey Chris,

your sugesstions sound reasonable to me. I'm currently preparing for a trip - is it OK for you if I a take a deeper look in the upcoming days? Will get back to you on Monday at the latest.

feO2x commented 1 year ago

Hey Chris,

I found some time early in the morning to take a closer look. I totally agree with everything you presented and I would add the following methods.

Method name Safe? Reason
MustBeOfType Only performs an explicit cast with the as operator which cannot cause enumeration
IsSameAs Calls ReferenceEquals which cannot result in enumeration
MustNotBeSameAs See IsSameAs

I had a look at your branch, looks good to me. What's your opinion on these three additional methods? Would you be so kind and add the NoEnumerationAttribute to these methods, too, if you agree with me? Could you then please create a pull request that would merge with the dev branch? Thanks so much for your efforts in advance!

feO2x commented 1 year ago

The new version 10.1.0 is now released and contains your changes! https://www.nuget.org/packages/Light.GuardClauses/10.1.0