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

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).

Related

Best practice: Validate conditions for method calls?

I guess in almost every programm sometimes methods don't need to be called all the time but under specific conditions only.
It it very easy to check if a method must be called. A simple if-statment can do the trick.
if (value == true)
{
DoSomething();
}
But if you have many conditions the validation can get complicated and the code gets longer and longer.
So I wrote code with the method called every time
and the method itself will check and validate if her code needs to be executed.
DoSomething(value);
... then ...
public void DoSomething(bool value)
{
if (value == true)
{
// Do Something here ...
}
}
Now I have two ways of doing things. I am not exactly sure which way is the right way.
Or maybe there is even another option?
Clean Code — A Handbook of Agile Software Craftsmanship promotes not to write methods accepting a single boolean parameter because each method should do one thing and one thing only. If a method takes a boolean parameter to decide what to do, it automatically does two things: deciding what to do and actually doing something. The method should be refactored into two separate methods doing something and a single method deciding which of the two methods to call.
Furthermore, evaluating a boolean value using value == true is redundant and unnecessary. The value itself represents a boolean state (true / false) and does not need to be compared to true again. That said, the best practice is using if (value) instead of if (value == true) (or if ((value == true) == true; this seems idiotic but does not differ much from the approach of if (value == true)).
I find the answer to this question to be fairly obvious - unless I'm missing something. Adapt to each situation.
The called function should do what it's intended to do. If its intention is to work on some set of arguments, by all means do the checking inside the function.
If you plan to call the function conditionally, do the checking outside.
Moving the check inside just so you can save some extra verification is not a good idea I think, since others might want to call your function and not know whether it actually works given their parameters. I say, unless checking inside is imperative, leave the checking outside.
EDIT:
I just re-read your question...
You basically have:
void foo(bool actuallyExecuteFoo)
{
////
}
Really? REALLY?
But if you have many conditions the validation can get complicated and the code gets longer and longer.
If the validation is complicated, it means that the logic underneath is complicated. Expect your code to be as complicated as your logic - it has to be somewhere out there, right? Just think how to write it in a clean way. And the clean way is not always the shortest way.
I recommend this variant:
if (value == true)
{
DoSomething();
}
Why? Because:
the code calling DoSomething is then more clear (*), as it explicitly shows when the logic of DoSomething should be executed and when not,
DoSomething itself depends on less parameters (which makes it more generic and reusable).
*) Yes, "more clear" actually means "longer" here, but it also means "explicit" and "self-documenting". The shorter variant actually tries to hide some logic, which makes the code less clear.
Check out this for C# not sure why you need C++ :)
If the method can throw a Argument/ArgumentNull Exception, then you should validate it before calling the method. Also, Microsofts Code Contracts, will tell you if you need to validate the input before calling the method, for any code using contracts (basically assertions for static analysis).
The general rule is not to validate the input more than necessary. If something isn't valid, you should throw a exception (C#), or return a error (C++). Not executing the code due to a invalid input, without telling why, makes it near-impossible for the next-developer to figure out what the problem is.
I would recommend the second way, but I have some remarks:
You do not need to check if (value == true), just check if (value) instead.
Return earlier, what I mean if (!value) { return; }
Second way will take more execution time, though code will look better. Why don't you use macro?
#define DOSOMETHING(value) if (value) {DoSomething();}
Replace all
if (value == true) {DoSomething(); }
with macro DOSOMETHING(value)
Your purpose will be solved and code will look better

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.

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?

What is the use of Nullable<bool> type?

a bool variable could hold true or false, while bool? could be null as well.
Why would we need a third value for bool ?
If it is not true, what ever it is, it is == false
Can you suggest a scenario where I would fancy a bool? instead.
Thanks
Something can be true, false or undefined for many reasons. How would one answer "Is your third child a girl?" if one only has two children? Both true and false are incorrect. Null would be appropriate as saying that the comparison doesn't apply.
Various answers discuss the importance of nullable types in general. There is an additional answer for the nullable boolean, specifically. It's hard to understand in C#, but very easy to understand if you look at null-valued logic in any database.
Let's say you're tracking a list or table of Shipments. A Shipment has a DeliveryDate, but of course you don't know this information until long after the shipment has been made, and probably at least a few days after the shipment was actually delivered, when UPS finally gets around to notifying you. So of course the DeliveryDate is a Nullable<DateTime> (or DateTime?).
You want to retrieve a list of all shipments that were delivered during the last week. So you write this:
var deliveredThisWeek = shipments.Where(s =>
s.DeliveryDate >= DateTime.Today.AddDays(-7));
Should shipments with a null delivery date be included? (The answer is, of course, no.)
OK, so what about this:
var deliveredBeforeThisWeek = shipments.Where(s =>
s.DeliveryDate < DateTime.Today.AddDays(-7));
Should shipments with a null delivery date be included in these results? The answer is still no.
So now you have a curious situation. You might think that between the two of these queries, you would receive all shipments in the system. A | !A is always true, right? Not when you're dealing with nulls.
Even this one fails to get you all the results:
var deliveredAnytime = shipments.Where(s =>
(s.DeliveryDate >= DateTime.Today.AddDays(-7)) ||
(s.DeliveryDate < DateTime.Today.AddDays(-7)));
So how is this possible?
In order to accurately represent this logic, you need a condition that is not true or false. And again, C# is kind of a bad example here because it doesn't implement the logic the way you'd really expect it to. But in SQLese, it makes sense, because:
[DeliveryDate >= BeginningOfWeek] = NULL
[DeliveryDate < BeginningOfWeek] = NULL
Clearly, NULL OR NULL is still NULL, not TRUE. That is how you can correctly say that a shipment was not delivered before the beginning of the week, and was not delivered after. Or, more accurately, we don't know when it was delivered, so we can't safely say that it does match either of those conditions.
But C# is not so consistent. In C#, if the DeliveryDate is null, then:
(s.DeliveryDate >= beginningOfWeek) == false
(s.DeliveryDate < endOfWeek) == false
Which gets you the right answer for our query above, so you might be tempted to say that regular boolean logic is good enough, except that this one messes it all up:
var deliveredThisWeek = shipments.Where(s =>
!(s.DeliveryDate < DateTime.Today.AddDays(-7));
Aha... now it's giving us back null delivery dates! This isn't right! And before someone says "#Aaronaught, what are you on about, of course it's right! Those shipments were NOT delivered before last week, so the condition should cover them!", stop and think about it for a second.
The NULL doesn't actually mean that they weren't delivered. The NULL means that we don't know when they were delivered. It's possible that a clerk will pick up the confirmation tomorrow, and fill in the DeliveryDate as two weeks ago, invalidating the data we just picked up. There should not be null instances coming back from that query, and yet there are. If you wrote the same query in SQL, those results would be excluded.
So, why should you care about Nullable<bool> when C# apparently doesn't? So you can avoid falling into this trap in your own code:
public static bool? IsThisWeek(DateTime? dt)
{
return (dt != null) ? (bool?)(dt.Value > DateTime.Today.AddDays(-7)) : null;
}
var deliveredBeforeThisWeek = shipments.Where(s =>
(!IsThisWeek(s.DeliveryDate) == true));
// Or, the equivalent:
var alsoDeliveredBeforeThisWeek = shipments.Where(s =>
(IsThisWeek(s.DeliveryDate) == false));
This is a bit awkward, but correct. We've written a query that more or less communicates its intent properly, and (bool?)null does not equate to true or false, so we get the right results in both cases.
If you ever need to evaluate a condition where the answer might be "I don't know" - use a bool? (AKA Nullable<bool>) as the result.
That way, the caller can decide how to handle an "I don't know" response instead of you simply choosing a default. Anything else means your class is lying.
a null value means "no value" or "unknown value". In this case, it's not true nor false, but undefined.
See: http://en.wikipedia.org/wiki/Many-valued_logic
It's good for when something hasn't been answered yet - think of a questionnaire. You have a list of y/n questions and only some have been answered. You wouldn't want to post true or false to the database table because the user hasn't answered the question yet.
it could be unknown in addition to true or false..in database land a NULL usually means unknown or no value
Lazy programming!
public bool MyProp
{
get { return (myProp = myProp ?? GetPropValue()).Value; }
}
private bool? myProp;
Well I could see it being used as a "Not determined yet" kind of thing, i use bools all the time and sometimes just two values isnt enough!! for instance:
bool? bl;
bl = true; //Yes
bl = false; //No
bl = null; // Not determined, so do nothing
in my opinion its just the third value to a bool.
a null value means
I don't know.
Insufficient data at this time
The state of the cat before the box is opened
I haven't made up my mind yet
Profit
a null value means Mu
I used it in a Filter Value. Basically I have a bool field in the database, but I wanted three states: Only return rows where the value is true, only return rows where the value is false, do not filter and return all rows.
Without a nullable bool I would have to use either an enum or a second bool to determine "Filter by this field yes/no" which would add bloat.
being nullable could indicate that the bool has not be set or initialized if that is something your program might need to know
If you’re about to use a Nullable bool, I would consider using an Enum or other data structure instead. It may help you avoid mistakes when the meaning of NULL is not known.
Recently, I mishandled a Nullable bool. I won’t go into the details of the mistake, but lets just say it was bad enough to require a full rollback. I began to wonder how practical it is to use in most applications. (In part in an attempt to hold on to my broken pride as a result of the stupid mistake 🙂 )
Then, I came across this post and Lee's accepted answer.
This seems to make sense, but the more time I spend with it, the answer becomes FALSE in practice instead of NULL. NULL is just too fuzzy.
Before answering this question one would have to assign a very specific meaning to NULL. Does NULL mean there was an error in the calculation? What if there is an error in the calculation before it is determined that there are only two children? (I would also argue that if there are indeed only two children, this could be handled before the question was posed to the program.)
Because we do not know what NULL means and because it is most definitely not TRUE (because, how could it be?) the BEST answer is FALSE.
Also, if this question indeed returns NULL, we’ve introduced a new definition to the domain. What is the scope of this definition?
So it would appear that TRUE or FALSE states represent a certainty regarding an outcome. NULL can be conceived of in at least three different states. For example, the statement “Thomas went to the bar last night.”
TRUE – Yes, Thomas went to the bar. (likeliest answer if you knew Thomas)
FALSE – No, Thomas did not go to the bar.
NULL – Huh?
Knowable – Something went wrong in the first calculation. E.g. you asked Thomas the question but sneezed while he replied , rendering you deaf momentarily. Simply asking him again will get you the answer.
Unknowable – The bar burned down and Thomas skipped town. There is no realistic way of getting the answer. (Please don’t poke holes in this, but I know you will)
Not applicable – See the example above regarding the three children, but, bars and Thomases instead.
What does NULL mean here? Determining what NULL means must be performed on a case by case basis. This is why I believe it is often better to use an Enum or other structure as it more gracefully exposes the intention behind a non-binary return value.
You'd want to use that to cover the situation of "what if the user doesn't specify neither true nor false?"
It's just a way to cover all possible outcomes.
Let's say that an order has been placed but not shipped yet. What is the value of Order.ShippedDate?
The old-fashioned way to handle this was to use a magical value like DateTime.MinValue. There were other ways to solve this problem (for example a wrapper type or an additional bool flag indicating that the order has not shipped yet). None of these is very satisfactory. What is needed is a uniform way to handle the problem of a missing or unknown value.
So the modern approach is to allow Order.ShippedDate to take on a value that semantically captures that the order has not shipped yet. That's the role that nullable types play. Semantically you should think of an instance of Nullable<T> with HasValue being false as representing "missing" or "unknown."
Further, databases have long allowed a column to allows null. For example, you could have an integer-valued column that allows null. How do you interact with such a column from code if you don't allow nullable ints? Again, you could use the approaches mentioned above but it is so much nicer when the language has a built-in facility for semantically capturing the situation that we are trying to model.
Here is another use case. Think of a hierarchical data structure that has a boolean property. Setting such property on the parent will apply to all of its children, unless those are set explicitly. Think Read only permissions for files and folders in Windows (which DO have a tri-state checkbox).
Parent1(readonly: true, evaluates true)
|-Parent2(readonly: null, evaluates true)
|-Child1(readonly: false, evaluates false)
|-Child2(readonly: null, evaluates true)
|-Parent3(readonly: false, evaluates false)
|-Child1(readonly: false, evaluates false)
|-Child2(readonly: null, evaluates false)
I think the primary motivation (at least it was presented like this :-)) for adding nullable types in C# 2 were databases. In database, any data type can have the NULL value and when mapping these to C#, this is a problem. Nullable types allow you to deal with this quite elegantly - you can use int?, bool? and others. They are used for example in LINQ to SQL.
What does the third value mean for booleans, that of course depends on the application. I guess that typically, it will mean that the value/field is not available.

Code suggestions by Resharper making code less readable?

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.)

Categories

Resources