Code suggestions by Resharper making code less readable? - c#

While trying to get to all green, i got the following suggestion by Resharper.
Original code:
static public string ToNonNullString(this XmlAttribute attr)
{
if (attr != null)
return attr.Value;
else
return string.Empty;
}
Suggestion: remove redundant 'else' resulting in following:
static public string ToNonNullString(this XmlAttribute attr)
{
if (attr != null)
return attr.Value;
return string.Empty;
}
To me, the suggested version seems less readable than the original. Does Resharper suggestion reflect the definition of good maintainable code?

Technically Resharper is correct in that the "else" is unnecessary, I prefer the former version though as the intent is more obvious.
Having said that, I'd rather go with:
return attr != null ? attr.Value : string.Empty;

Ah, code aesthetics. Holy war time. (ducks)
I'd go with either a ?: expression:
return attr != null ? attr.Value : String.Empty
or invert the if and remove the line break to produce a guard clause:
if (attr == null) return String.Empty;
return attr.Value;

I think the new version is much better if you invert the if
static public string ToNonNullString(this XmlAttribute attr)
{
if (attr == null)
return string.Empty;
return attr.Value;
}
Because your original version is too symmetric, while null-case is a special case.
New version is more readable in the terms of "what does it return most of the time?".

I agree that the first version of your code is more readable.
I've found Resharper suggestions in these cases to not always be helpful, although sometimes it can clean things up. That's why I've configured Resharper to show the change as a "Hint" rather than "Suggestion". This causes the green underline to be less visible and it won't be highlighted in the right sidebar.

If you do not like the way ReSharper suggests something, just disable the specific suggestion (slash warning slash hint). The same goes for coding style, which I think is quite highly configurable. Claiming ReSharper to be unusable (quoting "I'm happy to say it didn't survive, nobody here is using it anymore") just because you do not take 5 minutes to get know how to configure it is just plain stupid.
Of course you should not let some tool dictate some part of your coding style, and ReSharper is NOT doing that if you tell it not to. It's that simple.

Your original code is much more readable and understandable - at a glance, you can see exactly the condition which causes string.Empty to be returned. Without the else, you have to see that there is a return in the if block before that.
Just remember, you're a human and inherently smarter than the machine. If it tells you something is better and you don't agree, then don't listen to it.

My coding standard is always use brackets (even if there is only one instruction after if command)
This is requires a bit effort (more typing) but I so often become convinced that it is very worth it!
One of most common bug (and paradoxically difficult to find) is adding additional instruction after if statement and forgetting adding brackets...
So I like what Resharper proposed. Especially when having nested if-statements:
Assume we have this code:
if (condition1) {
instruction1;
}
else {
if (condition2) {
instruction2;
}
}
It can be changed to look like this:
if (condition1) {
instruction1;
}
else if (condition2) {
instruction2;
}
And this is much more readable to me then before.
(It would be also more visible when you have more than 2-level nested statements)

I've noticed the same thing about ReSharper so I do appreciate its ability to turn some items off or downgrade their warning level. I also am perplexed by this suggestion:
SomeClass varName = new SomeClass();
has a suggested change to:
var varName = new SomeClass();
Yes, I know that I don't need the initial declaration type but it feels odd to suggest that the var form is somehow better than the other. Is anyone familiar with the rationale behind the suggestion or do you agree with me that this one is odd as well?

Classic example of the exceptions that creep into everything when you use a small sample size. Refactoring a huge if-elseif-else block into a guard clause layout makes code far more readable, but, as you say, if you apply the same rules to a single if-else it's not as helpful. I'd go so far as to say it was a (slight) lack of foresight by the resharper devs not to skip over very small blocks such as this, but it's harmless enough.

Being a noob at C# and more used to C and Java I still can't get used to the placement of angle brackets in C# .NET and VS. Putting all that aside, I agree with Andrey in that inverting the 'if' is even more readable. On the other hand I personally find that omitting the 'else' reduces readability (slightly). I would go with this personally:
static public string ToNonNullString(this XmlAttribute attr)
{
if (attr == null)
return string.Empty;
else
return attr.Value;
}

The only thing I'd add would have to to with the length of the expressions involved. Personally, I like the compactness of ternary expressions, but turning something like
if (testDateTime > BaseDateTime)
return item.TransactionDate <= testDateTime && item.TransactionDate >= BaseDateTime;
return item.TransactionDate >= testDateTime && item.TransactionDate <= BaseDateTime;
into something like
return testDateTime > BaseDateTime ? item.TransactionDate <= testDateTime && item.TransactionDate >= BaseDateTime : item.TransactionDate >= testDateTime && item.TransactionDate <= BaseDateTime;
doesn't really seem helpful to me.

Its always debatable when it comes to best practices and coding standards. One of the reason for this is they cannot be enforced very easily using an IDE like Visual Studio. There are tools available like FxCop and StyleCop which can be used to analyse the code for standards. FxCop is used for compiled code analysis and StyleCop is used for source code analysis.
You can configure StyleCop to a minute level as to which formatting you would like to apply to the code. There is an add-in called StyleCop for Resharper which gives suggessions right inside Visual Studio. I had a detailed blog post about the same at
http://nileshgule.blogspot.com/2010/10/refactoring-clean-code-using-resharper.html

The resharper version is better as the 'attr != null' condition can be seen as an early bailout (or use-case exception path), allowing the function to continue on with its main task. (neither win high fives from me, I hate multiple returns).
In this case I'd say MrWiggles single-liner is the best alternative.

Some colleagues of mine started using Resharper from that moment on pages they edited were terrible in layout and readability. I'm happy to say it didn't survive, nobody here is using it anymore.
About the statement at hand i agree with Jeffrey Hantin, the inline-if is very nice for such a type of statement and Whatsit's solution is highly accaptable to. With some exceptions i (personaly) say methods/functions should have only 1 return statement.
Also if you (almost) always implement the else with your if (even if it's nothing else but a comment-line stating you do nothing in with the else-statement) it forces you to think about that situation, more often than not it can prevent mistakes.
Both remarks should be used as a 'think about' not like a rule, just like most of this kind of issues, always use your brain :) most errors occur when you don't.
In conclusion: Say NO to Resharper! (yes, I truely dislike Resharper, sorry.)

Related

Is there a simpler way to call Contains() on a string that is potentially null?

Is there a simpler or less ugly way to call .Contains() on a string that is potentially null then by doing:
Assert.IsTrue((firstRow.Text ?? "").Contains("SomeText"));
I'd suggest using Assert.That syntax:
Assert.That(firstRow.Text, Does.Contain("SomeText"));
If you need to check that text is not containing a certain string:
Assert.That(firstRow.Text, Does.Not.Contain("SomeText"));
I think any of these alternatives are better, even though they are not quite as short:
// 1
Assert.IsTrue(firstRow.Text != null && firstRow.Text.Contains("SomeText"));
// 2
Assert.IsNotNull(firstRow.Text);
Assert.IsTrue(firstRow.Text.Contains("SomeText"));
// 3
var text = firstRow.Text;
Assert.IsTrue(text != null && text.Contains("SomeText"));
I think "simple" is a subjective term. Simple, to me, means "clear and easy to read", not "fewest number of characters".
Considering that this code appears to be part of a unit test, Option #2 would be best, because then you can tell from reading the test results whether the test failed due to a null value or failed because the value did not contain the expected text. Otherwise, you would have to re-execute this test with a debugger and look at the value at runtime in order to distinguish between these two cases.
"Make things as simple as possible, but not simpler." - Albert Einstein
This is one character shorter, but frankly I like your original code better.
Assert.IsTrue((firstRow.Text + "").Contains("SomeText"));
No, there aren't any. But you could write an extension method for that:
public static bool SContains(this string source, string query)
{
return source != null && source.Contains(query);
}
I would expect the string being null exposes a different error to the string not being "SomeText", in which case it would be better to have two unit tests to test the different outcomes.
In terms of methods how about using StringAssert and IsNotNull?
Assert.IsNotNull(firstRow.Text);
StringAssert.Contains(firstRow.Text, "SomeText");
(I am assuming this relates to a unit test)
According to http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.stringassert(v=vs.100).aspx
StringAssert class can be used to easily assert whether or not the stringUnderTest contains the specefied string
I think a plain No,
This would be a little less ugly and gets the implied readability
If(!string.IsNullOrEmpty(firstRow.Text))
Assert.IsTrue(firstRow.Text.Contains("SomeText"));
I would generally use something more like the following which is longer and less clever but idiomatic c# and the intent is obvious.
Assert.IsTrue( !string.IsNullOrWhiteSpace(firstRow.Text))
Assert.IsTrue( firstRow.Text.Contains("SomeText"));
In my interpretation of the question, the empty string is an error condition. That's one reason I prefer my version - the context for the test is explicit. If I wanted to include the empty string as a valid result I would use the following as the first condition, again making the test explicit:
Assert.IsNotNull(firstRow.Text)
To me this is far more important than shortening the code. In a month when I (or someone else) come back to make changes to the code it is obvious what the intent of the test is. In the original question, not so much.

Use of else statement vs unused assignment

I have a similar question to the one posted here:
I have an if statement in an mvc controller that looks like this:
if (submitButton != "Search")
{
ModelState.Clear();
}
TempData["searchParameter"] = searchParameter;
however if the condition is false, TempData["searchParameter"] is never used. Is it a better practice to leave the code as above or put the TempData["searchParameter"] assignment in an else statement?
Put it in an else statement.
It makes the logic flow more explicit and an unnecessary operation is omitted, which affects the performance positively.
Id use the else statement. Makes it clearer and securer if any changes are made in the future.
I guess its also good practice.
In your example, TempData["searchParameter"] is assigned to regardless of of whether submitButton != "Search". Is this the behaviour you are expecting?
If not, an else statement will resolve this for you.
In your specific case, running unnecessary code is never a good idea when it can be easily avoided. It may not seem like a big deal in this case, but it is not a good habit to get into.
More generally, I always use an else statement even when the code flow would be identical without it. For example:
if(null == foo) {
return false;
} else {
foo.Bar();
return true;
}
The else is not strictly necessary, and some code analysis tools will recommend removing it. But I prefer the explicitness of being able to tell just by glancing at the structure of the code that only one of those blocks is actually going to be executed. Without the else, you have to analyze the first block to determine that it is exclusive of the second block.

LINQ or foreach - style/readability and speed

I have a piece of code for some validation logic, which in generalized for goes like this:
private bool AllItemsAreSatisfactoryV1(IEnumerable<Source> collection)
{
foreach(var foo in collection)
{
Target target = SomeFancyLookup(foo);
if (!target.Satisfactory)
{
return false;
}
}
return true;
}
This works, is pretty easy to understand, and has early-out optimization. It is, however, pretty verbose. The main purpose of this question is what is considered readable and good style. I'm also interested in the performance; I'm a firm believer that premature {optimization, pessimization} is the root of all evil, and try to avoid micro-optimizing as well as introducing bottlenecks.
I'm pretty new to LINQ, so I'd like some comments on the two alternative versions I've come up with, as well as any other suggestions wrt. readability.
private bool AllItemsAreSatisfactoryV2(IEnumerable<Source> collection)
{
return null ==
(from foo in collection
where !(SomeFancyLookup(foo).Satisfactory)
select foo).First();
}
private bool AllItemsAreSatisfactoryV3(IEnumerable<Source> collection)
{
return !collection.Any(foo => !SomeFancyLookup(foo).Satisfactory);
}
I don't believe that V2 offers much over V1 in terms of readability, even if shorter. I find V3 to be clear & concise, but I'm not too fond of the Method().Property part; of course I could turn the lambda into a full delegate, but then it loses it's one-line elegance.
What I'd like comments on are:
Style - ever so subjective, but what do you feel is readable?
Performance - are any of these a definite no-no? As far as I understand, all three methods should early-out.
Debuggability - anything to consider?
Alternatives - anything goes.
Thanks in advance :)
I think All would be clearer:
private bool AllItemsAreSatisfactoryV1(IEnumerable<Source> collection)
{
return collection.Select(f => SomeFancyLookup(f)).All(t => t.Satisfactory);
}
I think it's unlikely using linq here would cause a performance problem over a regular foreach loop, although it would be straightforward to change if it did.
I personally have no problem with the style of V3, and that one would be my first choice. You're essentially looking through the list for any whose lookup is not satisfactory.
V2 is difficult to grasp the intent of, and in its current form will throw an exception (First() requires the source IEnumerable to not be empty; I think you're looking for FirstOrDefault()). Why not just tack Any() on the end instead of comparing a result from the list to null?
V1 is fine, if a bit loquacious, and probably the easiest to debug, as I've found debugging lambdas to be a bit persnickety at times. You can remove the inner braces to lose some whitespace without sacrificing readability.
Really, all three will boil down into very similar opcodes; iterate through collection, call SomeFancyLookup(), and check a property of its return value; get out on the first failure. Any() "hides" a very similar foreach algorithm. The difference between V1 and all others is the use of a named variable, which MIGHT be a little less performant, but you have a reference to a Target in all three cases so I doubt it's significant, if a difference even exists.

Do you like languages that let you put the "then" before the "if"?

I was reading through some C# code of mine today and found this line:
if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) return;
Notice that you can tell without scrolling that it's an "if" statement that works with ItemContainerGenerator.Status, but you can't easily tell that if the "if" clause evaluates to "true" the method will return at that point.
Realistically I should have moved the "return" statement to a line by itself, but it got me thinking about languages that allow the "then" part of the statement first. If C# permitted it, the line could look like this:
return if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated);
This might be a bit "argumentative", but I'm wondering what people think about this kind of construct. It might serve to make lines like the one above more readable, but it also might be disastrous. Imagine this code:
return 3 if (x > y);
Logically we can only return if x > y, because there's no "else", but part of me looks at that and thinks, "are we still returning if x <= y? If so, what are we returning?"
What do you think of the "then before the if" construct? Does it exist in your language of choice? Do you use it often? Would C# benefit from it?
Let's reformat that a bit and see:
using System.Windows.Controls.Primitives;
...
if (ProgenyList.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
{
return;
}
Now how hard is it to see the return statement? Admittedly in SO you still need to scroll over to see the whole of the condition, but in an IDE you wouldn't have to... partly due to not trying to put the condition and the result on the same line, and party due to the using directive.
The benefit of the existing C# syntax is that the textual order reflects the execution order - if you want to know what will happen, you read the code from top to bottom.
Personally I'm not a fan of "return if..." - I'd rather reformat code for readability than change the ordering.
I don't like the ambiguity this invites. Consider the following code:
doSomething(x)
if (x > y);
doSomethingElse(y);
What is it doing? Yes, the compiler could figure it out, but it would look pretty confusing for a programmer.
Yes.
It reads better. Ruby has this as part of its syntax - the term being 'statement modifiers'
irb(main):001:0> puts "Yay Ruby!" if 2 == 2
Yay Ruby!
=> nil
irb(main):002:0> puts "Yay Ruby!" if 2 == 3
=> nil
To close, I need to stress that you need to 'use this with discretion'. The ruby idiom is to use this for one-liners. It can be abused - however I guess this falls into the realm of responsible development - don't constrain the better developers by building in restrictions to protect the poor ones.
It's look ugly for me. The existing syntax much better.
if (x > y) return 3;
I think it's probably OK if the scope were limited to just return statements. As I said in my comment, imagine if this were allowed:
{
doSomething();
doSomethingElse();
// 50 lines...
lastThink();
} if (a < b);
But even just allowing it only on return statements is probably a slippery slope. People will ask, "return x if (a); is allowed, so why not something like doSomething() if (a);?" and then you're on your way down the slope :)
I know other languages do get away with it, but C#'s philosophy is more about making The One Right WayTM easy and having more than one way to do something is usually avoided (though with exceptions). Personally, I think it works pretty well, because I can look at someone else's code and know that it's pretty much in the same style that I'd write it in.
I don't see any problem with
return 3 if (x > y);
It probably bothers you because you are not accustomed to the syntax. It is also nice to be able to say
return 3 unless y <= x
This is a nice syntax option, but I don't think that c# needs it.
I think Larry Wall was very smart when he put this feature into Perl. The idea is that you want to put the most important part at the beginning where it's easy to see. If you have a short statement (i.e. not a compound statement), you can put it before the if/while/etc. If you have a long (i.e. compound) statement, it goes in braces after the condition.
Personally I like languages that let me choose.
That said, if you refactor as well as reformat, it probably doesn't matter what style you use, because they will be equally readable:
using System.Windows.Controls.Primitives;
...
var isContainersGenerated =
ProgenyList.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated;
if (!isContainersGenerated) return;
//alternatively
return if (!isContainersGenerated);
There is a concern reading the code that you think a statement will execute only later to find out it might execute.
For example if you read "doSomething(x)", you're thinking "okay so this calls doSomething(x)" but then you read the "if" after it and have to realise that the previous call is conditional on the if statement.
When the "if" is first you know immediately that the following code might happen and can treat it as such.
We tend to read sequentially, so reading and going in your mind "the following might happen" is a lot easier than reading and then realising everything you just read needs to be reparsed and that you need to evaluate everything to see if it's within the scope of your new if statement.
Both Perl and Ruby have this and it works fine. Personally I'm fine with as much functionality you want to throw at me. The more choices I have to write my code the better the overall quality, right? "The right tool for the job" and all that.
Realistically though, it's kind of a moot point since it's pretty late for such a fundamental addition in C#'s lifecycle. We're at the point where any minor syntax change would take a lot of work to implement due to the size of the compiler code and its syntax parsing algorithm. For a new addition to be even considered it would have to bring quite a bit of functionality, and this is just a (not so) different way of saying the same thing.
Humans read beginning to end. In analyzing code flow, limits of the short term memory make it more difficult to read postfix conditions due to additional backtracking required. For short expressions, this may not be a problem, but for longer expressions it will incur significant overhead for users that are not seasoned in the language they are reading.
Agreed with confusing , I never heard about this construction before , so I think correct way using then before if must always contents the result of else, like
return (x > y) ? 3 : null;
else way there is no point of using Imperative constructions like
return 3 if (x > y);
return 4 if (x = y);
return 5 if (x < y);
imho It's kinda weird, because I have no idea where to use it...
It's like a lot of things really, it makes perfect sense when you use it in a limited context(a one liner), and makes absolutely no sense if you use it anywhere else.
The problem with that of course is that it'd be almost impossible to restrict the use to where it makes sense, and allowing its use where it doesn't make sense is just odd.
I know that there's a movement coming out of scripting languages to try and minimize the number of lines of code, but when you're talking about a compiled language, readability is really the key and as much as it might offend your sense of style, the 4 line model is clearer than the reversed if.
I think it's a useful construct and a programmer would use it to emphasize what is important in the code and to de-emphasize what is not important. It is about writing intention-revealing code.
I use something like this (in coffeescript):
index = bla.find 'a'
return if index is -1
The most important thing in this code is to get out (return) if nothing is found - notice the words I just used to explain the intention were in the same order as that in the code.
So this construct helps me to code in a way which reflects my intention slightly better.
It shouldn't be too surprising to realize that the order in which correct English or traditional programming-language grammar has typically required, isn't always the most effective or simplest way to create meaning.
Sometimes you need to let everything hang out and truly reassess what is really the best way to do something.
It's considered grammatically incorrect to put the answer before the question, why would it be any different in code?

Which is clearer form: if(!value) or if(flag == value)?

I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preference for one form over the other.
Obviously, the best answer is "refactor the code so you don't need to test for falsehood" but sometimes there's no easy way to do so and the "else" branch is simply to continue processing. So when you must have an "if not false" construct, which is the preferred standard:
The not operator
if (!value)
Or the test for false
if (value == false)
if (!value) is easier/faster to follow. Subjective as you said. As long as you are consistent, this is the main thing.
EDIT
One other point to add - omitting the true/false keywords should also (hopefully) force the coder to use better named variables. Bool variables should always indicate meaning or state purpose, such as:
if (MyWallet.IsEmpty)
There is no reason with the above to use == false or == true as it's redundant. The above is human readable immediately.
Far better than having to decipher:
if (MyWallet.EmptyStatus == true) or something ridiculous like this.
I personally like
if ((value == false) == true) ...
cause this is verifying that the statement value is false is actually evaluating to a boolean true...
and, then, obviously, covering both posssibilites adds even more clarity,
if ((value == false) == true && (value == false) != false)
<grin/>
and for those of you who are real gluttons for clarity, and demand incontrovertible readability, I'd suggest
if (((value == false) == true && (value == false) != false) == true)
But seriously, and I just thought of adding this, creating appropriate and meaningful variable Names is the key to this issue. You can easily, in the class where value is declared, add a computed variable as in (say "value "is actually "LaunchMissile"),
public bool AbortLaunch => !LaunchMissile,
then all you need is
if (AbortLaunch) ...,
and then it is terse, eminently readable, and avoids the negation operator.
if (!value)
This is always clearer in my opinion.
if (value == false)
I hate to say this, because it sounds kind of mean, but this normally shows that the person writing the code doesn't really understand the use of boolean values. You don't need to re-validate what a boolean is in an if statement. It's redundant.
(Personally, I would be annoyed at the person too if they named the variable value instead of something more meaningful. I have a feeling what you posted is just psuedo code, I would definitely ding that on a review.)
Edit (in response to a comment below):
It may look trivial, but often it is a sign of much bigger things. Truthfully, most people who do use var == true etc. don't understand. It's just a fact. I'm not saying their stupid or they shouldn't be programmers just that there is probably something that they need to review and learn. The problem is that when logic gets much more complex, not understanding concepts like this can lead to much much bigger problems down the road. Some people say "it's a style." That's fine. The real question in this case is, "How is it beneficial for me to do it this way? What do I or other people get from it?" If you can't solidly answer that question, then you need to ask yourself "Why is this a good idea?"
I would never use if(value == true), so just for consistency I would also not use if(value != false).
if(!value) is clearer and more "elegant", specially if you name boolean variables correctly
isWhatever
hasWhatever
etc
Something like
if (Page.IsPostback == true)
seems redundant to me
Dissenting opinion (kind of)
From a compilation standpoint, you're going to get the same IL, so it really only matters from a readability standpoint.
From that standpoint, the if(value == false) is more obvious to a casual reader, and there is less chance of missing the ! before the bool.
Honestly, I use both approaches, and most times, I make it depend on my variable name. If it still sounds ok to say "not" in place of the "bang", I'm likely to use the bang notation
e.g.
if(!gotValue) {}
//if (I've) not gotValue
//but
if(checkValue == false){}
//If (I've) not checkValue doesn't quite work here grammatically.
I use Not value when coding in VB but tend to use value == false when coding in C#. I find that the exclamation point can sometimes be lost in the name of the variable (e.g. !legal). Maybe it's because I'm, uh, a seasoned veteran.
I would favor using if(!value) because, depending on the names of the variables involved, the "true" case makes much more sense according to English semantics.
Consider one of the examples in this MSDN article:
if(pane.IsChecked)
reads in English as, "If the pane is checked".
However, if(pane.IsChecked == true) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.
One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "== true" makes this example more readable, and MSDN doesn't think so either.
Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.
I would normally prefer if (!value) too, when I know for sure that value is a boolean. But many times it can be a string, or a number.
The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).
Rant over. My suggestion: be explicit, especially if your language is the “very dynamic” type (i.e. JavaScript, PHP, Perl).
Whatever one you prefer. Pick one and stick to it.
I am sorry to say, the second just looks stupid to me.
I'd add an extra level, if someone prefers it:
if( (value==false) == true )
:)
I don't think it's all that subjective. I have never seen it recommended in the longer form. Actually all the books and coding guides and "How to be a good programmer" HowTos I've read discourage it.
It falls in the same category as
if (value) {
return true;
} else {
return false;
}
OTOH, all the answers given here make my first statement kinda equal not true.
I favour the if (!value) style at least for evaluating variables or common properties like Page.IsPostback and the like. For anything more complex I tend to parenthesise the expression like thus:
if (!(SomeType.SomeProperty.CallingAMethod(input).GetSomething.BooleanProperty))
Just to draw a little more attention to it.
All in all, it's an argument for Perl-style unless and until keywords.
If the condition is just a check of a single value, then !value is quicker.
However, when the condition contains multiple value checks, I find it much easier to read value == false. Somehow it is easier to parse multiple checks for equality than multiple negations of values.
I actually many of forms possible.
This is not actually how it is written to standards, but this is how I see it:
//if foo is(or exists)
if(foo)
//if foo is true
if(foo == true)
//if foo doesn’t exist
if(!foo)
if foo is false
if(foo == false)
Hence I don’t see == false is redundant.
I prefer the second option, the if (value == false) one.
I gladly use if (~value) or if (not value) in languages that support it, but that ! just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.
Also, two things:
I never do if (value == true), and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky ! is simply worse.
I think it's really a matter of personal taste, just like the brace-on-a-newline debate. I would never criticize a teammate for silly little things like that, and I have a hard time understanding the people who will.
I use if (value == false)
The ! in if (!value) is so small I sometimes miss it.
Whatever condition an if block should evaluate in order to execute must evaluate to true.
Hence, when value is false, the reason why if (!value) allows an if block to execute is because the ! operator essentially flips the false value of value to true, thus making the resultant condition within the parentheses evaluate into a true one that an if block needs in order to execute.
if (value), if (!value), if (flag == value), if (value == true), if (value == false), depending on what's to be achieved, are valid code. E.g. if (value == true) is very useful when value is a nullable boolean, because if (value) will give a syntax error, and if (value.Value == true) will throw exception if you didn't ensure that value is not null before the if block is executed.
I am also of the opinion that using == inside an if is redundant and I have another suggestion, at least visually, by introducing spaces:
if ( ! created)
Even using OpenDyslexic as font, the not sign ! next to the opening bracket ( can be too close to distinguish it at a glance if(!created).

Categories

Resources