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.
Related
I am currently studying C# and I really want to get a good coding style from the beginning, so I would like to hear opinions from you professionals on this matter.
Should you always (or mostly) use local variables for conditions/calculations (example 2) or is it just as good/better to use statements directly (example 1)
Example 1.
if (double.TryParse(stringToParse, out dblValue)) ...
Example 2.
bool parseSuccess = double.TryParse(stringToParse, out dblValue);
if (parseSuccess) ...
It would be interesting to hear your thoughts and reasoning at this example.
You should use the more verbose style if putting it all in one line would make it too long or complicated.
You should also use a separate variable if the variable's name would make it easier to understand the code:
bool mustWait = someCommand.ConflictsWith(otherCommand);
if (mustWait) {
...
}
In such cases, you should consider using an enum for additional readability.
I see a lot of example 1 in production code. As long as the expression is simple, and it's easy to understand the logic of what's happening, I don't think you'll find many people who think it is bad style.
Though you will probably find a lot of people with different preferences. :)
Heres the rule I use: Keep it on one line if you can quickly glance over it and know exactly what it's saying. If its too complicated to read as quickly as you could read any other text, give it a local variable. In any case, though, you don't want a really long if statement header. So if it's too long, split it up.
I suggest you use a local variable like here:
bool parseSuccess = double.TryParse(stringToParse, out dblValue);
if (parseSuccess) ...
For two reasons:
1. You can use more times the variable without parse your double another time.
2. It makes the code more readable.
Consider this:
if(double.TryParse(string1, out Value1) && double.TryParse(string2, out Value2) && double.TryParse(string3, out Value3) && double.TryParse(string4, out Value4))
{
//some stuff
}
It's too long and it makes the code hard to be read.
So sometimes local variabels make the code a lot more readable.
The clarity of the source code is an important parameter especially in application maintenance but so is performance.
Insignificant it may seem, sometimes using simple syntax "tricks" of programming languages​​, we get very good results.
If I think I'll use later in the code somehow the result, I use variables, otherwise I give priority to direct sentences.
There's no right option. Both are perfectly acceptable.
Most people choose the first option if you don't have a lot of conditions to concatenate because it results in less lines of code.
As you said you are studying C#
So my vote will be this style for you
bool parseSuccess = double.TryParse(stringToParse, out dblValue);
if (parseSuccess) ...
If you are studying you will have lot to learn and the above
style clearly tells you that TryParse return a bool, so you won't have
to worry or find whats the return type for TryParse
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.
He has something similar to the following:
var item = someObject.Where(user => user.Id == Id).Single();
Whereas I've been doing the following:
var item = someObject.Single(user => user.Id == Id);
Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.
The queries should be equal when the tree is evaluated, however depending on the target the actual execution could differ (IE L2S optimization).
I typically think in terms of "filter then take a single value". On the other hand, when it comes to Count I'll often use the version with the predicate. For Any I can go either way pretty easily depending on my mood :)
Ultimately it's unlikely to make any significant difference - use whichever is easier to understand at the time. I certainly wasn't trying to avoid using the versions with predicates etc - and I give some examples using them on P499.
While there are some situations with "definitely more readable" versions, many other cases are pretty much equally readable either way.
The only thing I can notice is that the IL produced using the Where method is one row bigger than the second example (tested through LinqPAD).
IL_0042: call System.Linq.Enumerable.Where
IL_0047: call System.Linq.Enumerable.Single
instead of a single call to System.Linq.Enumerable.Single
IL_006B: call System.Linq.Enumerable.Single
Specifically for Linq2Objects, I personally prefer using the Enumerable.Single(this, predicate) version directly, simply because adding the Enumerable.Where will introduce an additional enumeration which Enumerable.Single will pull the data from.
By using Enumerable.Single directly on the primary enumerable, no additional enumerations are started. I have never benchmarked this to evaluate the real performance impact, but why execute more code when you don't need to right? Especially if readability is not impacted, of course this last point is rather subjective.
I like readability.
So, I came up with an extension mothod a few minutes ago for the (x =! null) type syntax, called IsNotNull. Inversly, I also created a IsNull extension method, thus
if(x == null) becomes if(x.IsNull())
and
if(x != null) becomes if(x.IsNotNull())
However, I'm worried I might be abusing extension methods. Do you think that this is bad use of Extenion methods?
It doesn't seem any more readable and could confuse people reading the code, wondering if there's any logic they're unaware of in those methods.
I have used a PerformIfNotNull(Func method) (as well as an overload that takes an action) which I can pass a quick lambda expression to replace the whole if block, but if you're not doing anything other than checking for null it seems like it's not providing anything useful.
I don't find that incredibly useful, but this:
someString.IsNullOrBlank() // Tests if it is empty after Trimming, too
someString.SafeTrim() // Avoiding Exception if someString is null
because those methods actually save you from having to do multiple checks. but replacing a single check with a method call seems useless to me.
It is perfectly valid to do but I don't think it is incredibly useful. Since extension methods are simply compiler trickery I struggle to call any use of them "abuse" since they are just fluff anyhow. I only complain about extension methods when they hurt readability.
Instead I'd go with something like:
static class Check {
public static T NotNull(T instance) {
... assert logic
return instance;
}
}
Then use it like this:
Check.NotNull(x).SomeMethod();
y = Check.NotNull(x);
Personally it's much clearer what is going on than to be clever and allow the following:
if( ((Object)null).IsNull() ) ...
I don't entirely agree with the reasoning saying "it may confuse".
To some extent I can see what is meant, that there is no reason to venture outside "common understanding" -- everybody understands object != null.
But in Visual Studio, we have wonderful tools where you can simply hover over the method, to reveal some additional information.
If we were to say that the extension-method was annotated with a good explanation, then I feel that the argument of confusion falls apart.
The methods .IsNotNull() and .IsNull() explain exactly what they are. I feel they are very reasonable and useful.
In all honesty it is a matter of "what you like". If you feel the methods will make it more readable in the context of your project, then go for it. If you are breaking convention in your project, then I would say the opposite.
I have had the same thoughts as you have on the subject and have asked several very very experienced developers at my place of work. And none of them have come up with a good reason (except what has been mentioned about -confusion- here) that would explain why you shouldn't do this.
Go for it :-)
There is precedent, in as much as the string class has IsNullOrEmpty
You're also introducing method call overhead for something that's a CLR intrinsic operation. The JIT might inline it away, but it might not. It's a micro-perf nitpick, to be sure, but I'd agree that it's not particularly useful. I do things like this when there's a significant readability improvement, or if I want some other behavior like "throw an ArgumentNullException and pass the arg name" that's dumb to do inline over and over again.
It can make sense if you, for instance, assume that you might want to throw an exception whenever x is null (just do it in the extension method). However, I my personal preference in this particular case is to check explicitly (a null object should be null :-) ).
To follow the pattern it should be a property rather than a method (but of course that doesn't work with extensions).
Data values in the System.Data namespace has an IsNull property that determines if the value contains a DbNull value.
The DataRow class has an IsNull method, but it doesn't determine if the DataRow is null, it determines if one of the fields in the data row contains a DbNull value.
I am trying to create my first fluent interface and I was just wondering what other poeple thought was more fluent and which one they would prefer to use?
Check.Field().Named("est").WithValueOf("sdsd").IsNotNull()
Check.Field("est").WithValueOf("sdsd").IsNotNull()
Check.Field("est").WithValue("sdsd").IsNotNull()
Cheers
Anthony
Last one definitely:
Check.Field("est").WithValue("sdsd").IsNotNull()
I concur:
Check.Field("est").WithValue("sdsd").IsNotNull()
As short as possible, while still making sense.
Avoid noise words like .as. .of. .and. .in. unless they add contextual meaning. I've seen fluent interfaces that do this, and it adds nothing useful except more typing and more hoops for the application to jump through when it executes.
Another option might be:
Check.Field("est").IsNotNull("sdsd")
Something like LINQ's FirstOrDefault called with a predicate instead of filtering and then calling FirstOrDefault.
What is Check? I suspect it's not needed at all. I understand what you're trying to do, but remember that the expression you're trying to build will still likely end up in an if statement. With that in mind, think about how "if check X" reads. Not too well, imho. Additionally, what does the 'Field' function have to do to resolve that name? Do you have that somewhere else that you could present in a nicer way (perhaps an extension method on some base type?)
Or, to mimic some of the collections, use of Item property:
Check["est"].WithValue("sdsd").IsNotNull()
Some might also say you should just use .IsNull() and negate the whole expression, like this, but that's a "six -vs- half a dozen" thing:
!Check["est"].WithValue("sdsd").IsNull()
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What Advantages of Extension Methods have you found?
All right, first of all, I realize this sounds controversial, but I don't mean to be confrontational. I am asking a serious question out of genuine curiosity (or maybe puzzlement is a better word).
Why were extension methods ever introduced to .NET? What benefit do they provide, aside from making things look nice (and by "nice" I mean "deceptively like instance methods")?
To me, any code that uses an extension method like this:
Thing initial = GetThing();
Thing manipulated = initial.SomeExtensionMethod();
is misleading, because it implies that SomeExtensionMethod is an instance member of Thing, which misleads developers into believing (at least as a gut feeling... you may deny it but I've definitely observed this) that (1) SomeExtensionMethod is probably implemented efficiently, and (2) since SomeExtensionMethod actually looks like it's part of the Thing class, surely it will remain valid if Thing is revised at some point in the future (as long as the author of Thing knows what he/she's doing).
But the fact is that extension methods don't have access to protected members or any of the internal workings of the class they're extending, so they're just as prone to breakage as any other static methods.
We all know that the above could easily be:
Thing initial = GetThing();
Thing manipulated = SomeNonExtensionMethod(initial);
To me, this seems a lot more, for lack of a better word, honest.
What am I missing? Why do extension methods exist?
Extension methods were needed to make Linq work in the clean way that it does, with method chaining. If you have to use the "long" form, it causes the function calls and the parameters to become separated from each other, making the code very hard to read. Compare:
IEnumerable<int> r = list.Where(x => x > 10).Take(5)
versus
// What does the 5 do here?
IEnumerable<int> r = Enumerable.Take(Enumerable.Where(list, x => x > 10), 5);
Like anything, they can be abused, but extension methods are really useful when used properly.
I think that the main upside is discoverability. Type initial and a dot, and there you have all the stuff that you can do with it. It's a lot harder to find static methods tucked away in some class somewhere else.
First of all, in the Thing manipulated = SomeNonExtensionMethod(initial); case, SomeNonExtensionMethod is based on exactly the same assumptions like in the Thing manipulated = initial.SomeExtensionMethod(); case. Thing can change, SomeExtensionMethod can break. That's life for us programmers.
Second, when I see Thing manipulated = initial.SomeExtensionMethod();, it doesn't tell me exactly where SomeExtensionMethod() is implemented. Thing could inherit it from TheThing, which inherits it from TheOriginalThing. So the "misleading" argument leads to nowhere. I bet the IDE takes care of leading you to the right source, doesn't it?
What's so great? It makes code more consistent. If it works on a string, it looks like if it was a member of string. It's ugly to have several MyThing.doThis() methods and several static ThingUtil.doSomethingElse(Mything thing) methods in another class.
SO you can extend someone else's class. not yours... that's the advantage.
(and you can say.. oh I wish they implement this / that.... you just do it yourself..)
they are great for automatically mixing in functionality based on Interfaces that a class inherits without that class having to explicitly re implement it.
Linq makes use of this a lot.
Great way to decorate classes with extra functionality. Most effective when applied to an Interface rather than a specific class. Still a good way to extend Framework classes though.
It's just convenient syntactic sugar so that you can call a method with the same syntax regardless of whether it's actually part of the class. If party A releases a lib, and party B releases stuff that uses that lib, it's easier to just call everything with class.method(args) than to have to remember what gets called with method(class, args) vs. class.method(args).