How to check if object does NOT contain an item in NUnit? - c#

Is there a way to check if an object does NOT contain an item in NUnit? The NUnit.Framework.Assert.Contains() method checks if an item is contained, but I am looking for the opposite here. A lot of methods have a negative counterpart (like Assert.NotNull(), Assert.AreNotEqual() and Assert.DoesNotThrow()), but Contains() Seems to be lacking such an opposite method.
The only way I found is checking it manually using Assert.That(), but that is a little bit clunky and doesn't read as well.
Assert.That(!result.Dependencies.Contains<string>("tableName"));

I believe these should work:
Assert.That(result.Dependencies, Does.Not.Contain("tableName"));
Assert.That(result.Dependencies, Has.None.EqualTo("tableName"));
In general, the framework has not added new "Classic" assertions for some years. DoesNotContain would be easy to implement, so you can always ask the project for it if you prefer the older syntax.
#Commenters... The problem with Assert.That(bool condition) is that it doesn't give a very good error message, so I can understand why #Axel doesn't want to use it. Of course, it can be used with an error message specified, but that's more typing. :-)

Related

Roll your own assertion (and do something fun with the methods)?

I couldn't think of a way to describe what I'm trying to do for the question title--which may be why I couldn't just Google it. Any help either titling or Googling would be hot.
Here's the code I'm looking for:
Assert.That(true == false);
...or...
Assert.That(true == false).Else<ArgumentException>();
At this point, I can make the second one work or I can make the first one work. (The first one throws a very general "AssertionFailedException", which I would like to keep as the default in the event that the .Else() part isn't supplied.
Is there a way I can make these both work?
The problem is, by the time That has been evaluated by the runtime, it doesn't know there is an additional method call (Else) to make. Frameworks like NUnit use a different syntax that avoids this problem:
Assert.That(someValue, Is.Not.EqualTo(someOtherValue))
You construct a constraint, pass it to Assert.That, then NUnit does the actual validation and exception throwing.
You could introduce a syntax like this (using NUnit again as an example):
Assert.That(someValue, Is.Not.EqualTo(someOtherValue).Else<ArgumentException>());
That way, configuring what exception to throw if the assertion fails is simply part of the constraint configuration.

Does including prepositions at the end of method names follow or detract from normal C# API design?

I know this sounds like a subjective answer, but I will try to make the question as objective as possible, because an objective answer to the question would be the most helpful.
I recently had a code reviewer point out that I have a habit of including prepositions at the end of my methods. Here's a recent method I wrote as an extension method to the Point class:
var rectangle = new Rectangle(0, 0, 2, 2);
var point = new Point(3, 1);
var result = point.DistanceTo(rectangle);
My code reviewer mentioned that the method should be point.Distance(rectangle). I've always considered this subjective and a matter of style. However, I have noticed more .NET API design going in this direction. For example, with NUnit's Fluent Interface, you have:
Assert.That(result, Is.EqualTo(1.0));
I have also seen this with Linq:
list.CopyTo(anotherList);
list.IndexOf(item);
list.RemoveAt(0);
Is there any settled or consistent way that .NET and/or Third Party API designers use prepositions at the end of methods? Or is it just a matter of style, and subjective? Has the API design in the .NET framework itself evolved with this policy, or has it always been in place?
Prepositions are fine, as long as the object of the preposition is the corresponding argument (usually the first, never the this argument of an extension method).
An example where it might be an argument later than the first:
array.CopyCountedTo(count, destination);
To answer your question about whether this has evolved with .NET, no it hasn't.
Prepositions in function names are far more widespread than Microsoft (e.g. Java has string.charAt and string.indexOf), also .NET has been using it a lot longer than LINQ (e.g. ArrayList.IndexOf in .NET 1.0).
Agreed, it is subjective but I go with the premise that I don't want to have to "Go To Definition" to work out what a method call does. The name shouldn't expand into a novel but being descriptive certainly doesn't hurt.
My personal view on the matter is that prepositions enhance the meaning of the method name. I would never use them in property names, as they almost always seem to imply an action or calculation. To use the examples you offered from the framework:
RemoveAt clearly implies that it operates using a position, while Remove is vague; you don't discover its true meaning until you examine the parameters.
CopyTo implies both duplication and movement, whereas Copy alone only clearly implies duplication.
IndexOf tells us both the meaning of the return value and the method's parameter, while Index only hints at the return value.
So yeah, to summarise, I think it's perfectly legitimate -and- improves the readability and intuitiveness of code.
As you note, this is subjective, but I like to do this, and the fact the Linq uses it strikes me as an implicit approval from Microsoft.
I think the best and even historical approach that method name should have a verb. Because a method is an act, not a thing. This verb tells you a lot what method actually do (find, try, add, remove etc.)
I know you asked about prepositions. So considering exactly your example with noun-method Distance(), I feel it confusing. Ok, distance. What is about it?
If you see verbs will make your listings bigger and harder to read, then prepositions may become that powerful tool to help here. They are short and informative.
What if method would be a Vector. Its ambigious. VectorTo, VectorFrom - prepositions help.
ConvertToMesh() is long, Mesh() is too abstract, but ToMesh() is both short and clear.
One more plus of prepositions is a hint that method has required parameter. E.g. GetBy() makes clear that it expects something.

C#: Extension methods and the Not operator Best Practice

I have an array of strings and I wish to find out if that array does not contain a certain string. I can use the not operator (!) in conjunction with the Contains method like so:
if (!stringArray.Contains(searchString))
{
//do something
}
The not operator (!) might be overlooked when scanning the code so I was wondering if it was considered bad practice to create an Extension method in an attempt to enhance readability:
public static bool DoesNotContain<T>(this IEnumerable<T> source, T value)
{
return !source.Contains<T>(value);
}
So now the code could read:
if (stringArray.DoesNotContain(searchString))
{
//do something
}
Is this sort of thing frowned upon?
Keep the !. This is where a comment above the line would help readability.
(I suspect ! is more efficient)
//If the word is NOT in the array then...
Another point is to whether you are dead-set on using an Array?
There is something (that you may or may not know about) called a HashSet.
If your sole purpose is to examine whether or not a string is in a list, you are essentially looking at set arithmetic.
Unless you are using the array for something other than finding out whether a certain term is in it or not, try using a HashSet...much faster.
Personally, I wouldn't make an extension method for something so simple. I understand that you're trying to keep it readable but most C# developers should catch the ! operator. It's heavily used and even beginners usually recognize it.
Seems unnecessary, !source.Contains<T>(value); is pretty readable. Also, using the existing Contains function means that your code will be more portable (i.e., it won't be dependent on your extension method being present).
I would definitely use the !stringArray.Contains(string). This what 99.9% of all developers use. DoesNotContain would confuse me at least.
I think your question is based on a bit of a faulty premise. Namely that developers will read past the ! in your code. The ! boolean operator is a very well known operator in a large number of popular programming languages (C, C++, C#, Java, etc ...). Anyone who is likely to read past the ! on a regular basis probably shoudln't be checking in code without a heavy review before hand.
It feels like you`re saying the following
I want people to code in C# but I don't trust them to read it hence I'm going to create a new dialect in my code base with extension methods.
Why stop with the ! operator? It seems just as likely that they would miss the + in += expression or read a | as a ||.
Never seen DoesNot* methods in .NET framework, so I think your problem with ! is overestimated.
I guess this is a personnal choice more than a good/bad practice. IMO I like the extension methods since its more declarative thus more readable, at first glance you know exactly what it does. Just my 2 cents
This sounds like a bad idea, now the consumers of your code have to know about two methods (DoesNotContain and Contains) instead of just one. In general I would avoid XXNotXX methods.
I would personally make an extension method for that if I was going to be using that quite frequently within the project. If it is a one off then i wouldnt bother, but its not really bad practise.
The reason I would do it is because the if() has more context at a glance as to what is going on. Ok granted anyone with a brain cell would know what the current statement is doing, but it just reads nicer. Everyone will have their own preference then...
I made an extension method for formatting strings just to make the code flow better...
I prefer option 1 over option 2. Extension methods are very cool and are great to use for such things as conversions or comparisons that are used frequently. However, Microsoft does recommend to use extension methods sparingly.
I really would consider extension methods which does nothing else than negating an expression as bad practice.
What about:
if (stringArray.Contains(searchString) == false)
{
//do something
}
When !something doesn't work, then fall back to something == false.

Convention while using Helper Casting Functions

I recently began to start using functions to make casting easier on my fingers for one instance I had something like this
((Dictionary<string,string>)value).Add(foo);
and converted it to a tiny little helper function so I can do this
ToDictionary(value).Add(foo);
Is this against the coding standards?
Also, what about simpler examples? For example in my scripting engine I've considered making things like this
((StringVariable)arg).Value="foo";
be
ToStringVar(arg).Value="foo";
I really just dislike how inorder to cast a value and instantly get a property from it you must enclose it in double parentheses. I have a feeling the last one is much worse than the first one though
Ignoring for a moment that you may actually need to do this casting - which I personally doubt - if you really just want to "save your fingers", you can use a using statement to shorten the name of your generic types.
At the top of your file, with all the other usings:
using ShorterType = Dictionary<string, Dictionary<int, List<Dictionary<OtherType, ThisIsRidiculous>>>>;
I don't think so. You've also done something nice in that it's a bit easier to read and see what's going on. Glib (in C) provides casting macros for their classes, so this isn't a new concept. Just don't go overkill trying to save your fingers.
In general, I would consider this to be code smell. In most situations where the type of casting you describe is necessary, you could get the same behavior by proper use of interfaces (Java) or virtual inheritance (C++) in addition to generics/templates. It is much safer to leave that responsibility of managing types to the compiler than attempting to manage it yourself.
Without additional context, it is hard to say about the example you have included. There are certainly situations in which the type of casting you describe is unavoidable; but they're the exception rather than the rule. For example, the type of casting (and the associated helper functions/macros) you're describing extremely common-place in generic C libraries.

C# Compiler Enhancement Suggestion

Imagine someone coding the following:
string s = "SomeString";
s.ToUpper();
We all know that in the example above, the call to the “ToUpper()” method is meaningless because the returned string is not handled at all. But yet, many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “Why aren’t the characters on my ‘s’ variable capitalized”????
So wouldn’t it be great if there was an attribute that could be applied to the “ToUpper()” method that would yield a compiler error if the return object is not handled? Something like the following:
[MustHandleReturnValueAttribute]
public string ToUpper()
{
…
}
If order for this code to compile correctly the user would have to handle the return value like this:
string s = "SomeString";
string uppers = s.ToUpper();
I think this would make it crystal clear that you must handle the return value otherwise there is no point on calling that function.
In the case of the string example this may not be a big deal but I can think of other more valid reasons why this would come in handy.
What do you guys think?
Thanks.
Does one call a method for its side-effects, for its return value, or for both? "Pure" functions (which have no effects and only serve to compute a return value) would be good to annotate as such, both to eliminate the type of error you describe, as well as to enable some potential optimizations/analyses. Maybe in another 5 years we'll see this happen.
(Note that the F# compiler will warn any time you implicitly ignore a return value. The 'ignore' function can be used when you want to explicitly ignore it.)
If you have Resharper it will highlight things like this for you. Cant recommend resharper highly enough, it has lots of useful IDE additions especially around refactoring.
http://www.jetbrains.com/resharper/
I am not sure that I like this. I have called many a method that returns a value that I choose not to capture. Adding some type of default (the compiler generates a warning when a return value is not handled) just seems wrong to me.
I do agree that something along the suggested lines might help out new programmers but adding an attribute at this point in the game will only affect a very small number of methods relative the the large existing body. That same junior programmer will never get their head around the issue when most of their unhandled return values are not flagged by the compiler.
Might have been nice way back when but the horses are out of the barn.
I'd actually prefer a way to flag a struct or class as [Immutable], and have this handled automatically (with a warning) for methods called without using their return values on immutable objects. This could also protect the object by the compiler from changes after creation.
If the object is truly an immutable object, there really would be no way to handle it. It also could potentially be used by compilers to catch other common mistakes.
Tagging the method itself seems less useful to me, though. I agree with most of the other comments regarding that. If the object is mutable, calling a method could have other side-effects, so the above code could be perfectly valid.
I'm having flashbacks to putting (void) casts on all printf() calls because I couldn't get Lint to shut up about the return value being ignored.
That said, it seems like this functionality should be in some code checker tool rather than the compiler itself.
At least a compiler-warning would be helpful. Perhaps they add something similar for C# 4.0 (Design-By-Contract).
This doesn't warrant for a warning or pragma. There are too many places where it is intended to discard the result, and I'd be quite annoyed getting a warning/error from the compiler just because the method was decorated with some dodge attribute.
This kind of 'warning' should be annotated in the IDE's Editor, like a small icon on the gutter "Warning: Discarding return value" or similar.

Categories