|
Similarly, "if the door is locked" perform the same function as "if the door is locked is true".
In speech, noone that I know of includes the "is true". So why do you program as
if (doorIsLocked == true) ... rather than
if (doorIsLocked) ... I see no reason for or advantage of creating a more complex logical expression, adding a second, redundant element. Both "doorIsLocked" and "doorIsLocked == true" are logical expressions, the second one just more complex than it needs to be. (Hopefully, the compiler is able to optimize the redundant element away!)
If I program a test like
if (x < 10 && x < 20) ... all programmers I know would point out that it is redundant to test for "x < 20" if you already have tested that x < 10.
Adding an extra element a logical expression, to see whether a true "a" is equal to "true" (or that a false "a" is different from "true") is similarly redundant. The logical "a" expression is true or false, all by itself!
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
trønderen wrote: Religious freedom is the freedom to say that two plus two make five. Incorrect. Two plus two making five is provably incorrect. Religious freedom is the freedom to believe things that cannot be proven.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Religious freedom is the freedom to be irrational. If you reject all irrationality, then you reject religion. We cannot forbid irrationality and still claim that we have full religious freedom.
Using "two plus two make five" as an example is a way to make the irrationality (very) explicit.
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
Just noting that the semantics of how a logical expression is resolved in C++ is different than in C#/Java.
So the following is valid in C/C++
int v = 0;
if (v) {}
else {}
Because of operator overloading in C++ (to be fair it has been long time since I did this) I believe there can be situations where one must explicitly use the following. Leaving it out at a minimum might lead to a compiler error. I can't visualize a case where it would not lead to a compiler error but might be one and then it would lead to a different and incorrect result at least compared to the code below.
if (p == true) ...
|
|
|
|
|
Ah, the benefits of modern languages.
Waaay back in the 90s, using ANSI C (I was using VAX C and DEC C) the "guru" who had first designed the system, had defined TRUE as (0==0) and FALSE as (!TRUE) -- because these would be unambiguous and correct regardless of architecture (the same code had to work on QNX and DOS).
Personally, I dislike how K&R and ANSI C handle true and false.
|
|
|
|
|
I have frequently seen programmers from India use
if (variable == true){...}
in their code. I really don't understand it.
But to be fair, their variables names do not make it clear that it's a Boolean value. All of my Boolean variables' names are a Yes/No question (IsValid, DoneProcessing, DoUseQuotes, etc.) so it's obviously a Boolean. When your Boolean variables are named poorly (Validation, Finish, Quotes, etc.), then you need the "== Boolean" in order to know what is going on.
Bond
Keep all things as simple as possible, but no simpler. -said someone, somewhere
|
|
|
|
|
condition ? f() : g();
CI/CD = Continuous Impediment/Continuous Despair
|
|
|
|
|
Your kind suggestion ? I agree : I still agree;
|
|
|
|
|
My suggestion: Delete every "== true" that you have ever programmed. Delete every "== false" you have ever programmed and negate the logical expression.
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
I do not understand that code - could you please rewrite it as a regex?
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
As others have said, it depends on the context.
I prefer a ternary operator if I must choose between returning one of two results:
Foo foo = (condition ? Foo1 : Foo2);
For choosing different actions, I prefer the if/then/else style, even if it would be possible to write this as a ternary expression:
if (condition)
{
expressions1;
}
else
{
expressions2;
}
A "cascading" if/then/else is useful for subordinate cases:
if (condition1)
{
expressions1;
}
else
{
if (condition2)
{
expressions2;
}
else
{
expressions3;
}
}
Note that there is angoing debate whether good style requires that one wrap even single expressions in curly brackets. ( {...} }. If is usually not required by the language, but can help clarify the flow.
Note that there are cases where a "cascading ternary operator" can also be useful, and actually clearer than the "cascading if/then/else".
Freedom is the freedom to say that two plus two make four. If that is granted, all else follows.
-- 6079 Smith W.
|
|
|
|
|
In languages were the braces (other other syntax) is not required to block out an IF or ELSE block of code, I have seen many bugs where someone got it wrong, or edited it much later incorrectly. In my code reviews, I enforce having them for all cases because it's impossible to get wrong were the code block starts and stops; there is no interpretation of non-visible cues needed.
Bond
Keep all things as simple as possible, but no simpler. -said someone, somewhere
|
|
|
|
|
For a "minor matter of style", this got a lot of responses!
I use style#1 if it's clear that all possibilities have been exhausted, and the ? operator if possible.
But if there's a sequence of nested if statements and there's any possibility that not all combinations have been accounted for, I use style#2 with the throw statement after the else . Defensive coding takes very little time compared to that which is otherwise wasted hunting down mysterious bugs.
|
|
|
|
|
But you don't really mean something like?
if (expression)
{
}
else if (!expression)
{
}
else
{
throw(this and that);
}
|
|
|
|
|
No throw here. It's clear that something above will get executed, and the (!expression) is also redundant.
|
|
|
|
|
I will fite you over that code.
Check out my IoT graphics library here:
https://honeythecodewitch.com/gfx
And my IoT UI/User Experience library here:
https://honeythecodewitch.com/uix
|
|
|
|
|
As @GregUtas was pointing out, a lot of answers for a (bad) style question! So, I'll just add my own, just to increase the noise
First, although the OP doesn't specify, we have to assume that the code is C++, because it looks like it and in plain C true and false are not defined. Now, if it's C++, both styles are wrong as @sanderrossel pointed out. The extra fluff of "== true" or "== false" only adds space for confusion and potential errors like the program below illustrates.
#include <stdio.h>
int main()
{
int one = 1, two = 2;
if (one + two == true) {
printf("Miracle of miracles!\n");
} else if (one + two == false) {
printf("Another miracle!!\n");
} else {
printf("1+2 = 3, you moron!\n");
}
return 0;
} It compiles fine with just a warning about "unsafe mix of type 'int' and type 'bool' in operation". Unsafe indeed!
PS Assume a joker comes along and added to a header file:
#define true 3
Mircea
|
|
|
|
|
My personal opinion is that more typing leads to more bugs, so there needs to be a compelling reason in terms of the code expressing intent in order to add redundancy to it, which is what you're doing here.
I mean, it's probably somewhat subjective, but I don't find much value in your else with the additional test.
If anything it's sort of jarring to me, because just skimming it I would automatically think you're doing something "off book" so to speak with that else if , and I'd have to look at it twice to be sure what I was looking at. I don't like that.
So overall I prefer just the else in the buff, at least in the situation you presented.
Check out my IoT graphics library here:
https://honeythecodewitch.com/gfx
And my IoT UI/User Experience library here:
https://honeythecodewitch.com/uix
|
|
|
|
|
Do I understand you correclty? Do you mean somthing like ...
if((expression == true) == true) {...}
... is overkill?
|
|
|
|
|
honey the codewitch wrote: My personal opinion is that more typing leads to more bugs So, APL is the answer
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
For the discussion about '== true' and '== false' read this, it is worth the time: Boolean algebra - Wikipedia[^]
After get it all you will see among others why
a.) a boolean is either true or false and nothing other!
b.) 'A AND B' is the same like 'NOT(NOT A OR NOT B)' and also e.g. why 'A OR B' is the same like 'NOT(NOT A AND NOT B)'
modified 26-Jan-24 17:41pm.
|
|
|
|
|
Great Ghu NO!
1st style is fine. Everyone understands the else keyword.
2nd style is absolutely ripe for unintended bugs. You change the expression in the if () and then forget to make the corresponding change in the else if() .
In both cases checking "== true " is a code smell (you don't understand logical expressions) and redundant. Checking "== false " is misleading and an easy source of errors.
Software Zen: delete this;
|
|
|
|
|
re/ ==true/false To finally set the record straight I do not write that way. I write if(expression) and if(!expression) . I am not certain why I stuck the == true/false in the specimen. Perhaps to save readers the trouble of looking for the negation ! operator.
re/ 1st 2nd styles sometimes I favor the self documenting of the 2nd style for lengthy complex conditions except for the unintended consequence of compiler warnings stating not all paths return a value. So for that reason alone I will probably insist on 1st style.
re/ risking unintended bugs I am not worried as I am confident of being sufficiently careful also I do not expect the relevant code to require re-write. Though this is moot per above.
|
|
|
|
|
I prefer the K&R format and always use braces to promote code safety.
if (condition) {
...;
}
else {
...;
} /ravi
|
|
|
|
|
I make a sharp distinction between how I personally would like to format the code, and how I code when someone else will/might read it. I see so many errors caused by deep nesting and misinterpretation of indentation levels that I want a double check to detect mistakes. Therefore:
1) No indentation that is not supported by braces
2) No braces that do not adhere to the indentation level.
So if I see anything like
if (somecondtion)
xval = 1;
nextstatement; I immediately ask for permission to add the "redundant" braces. Most programmers accept this.
The second point is far less accepted: As long as you are not past the closing brace, you are still in the indented block. The brace is what causes the undent. Code is read in forward direction, so the last character position before the brace is still indented. Also, the closing brace visually blurs what is the next statement. I would really want to edit the above code to
if (somecondition) {
xval = 1;
}
nextstatement; - but few other programmers agree to the indentation of the closing brace. I have to tolerate what I consider a logical inconsistency, in non-private code. I also consider as inconsistent the style suggested by some:
if (somecondition)
{
xval = 1;
}
nextstatement; - you don't know that an indented block follows until after the opening brace. Inserting indenting space before it cannot be logically justified.
I honestly abhor deep block nesting, in particular when it ends up in a sequence of '} } } } }'. I try to avoid that whenever possible. Get out of a given nesting level as soon as possible! So I code like
FailureCode SomeMethod(int argX, float argY, sometype Z) {
if (argX > maxXvalue) {
return ErrorIllegalXArgument;
}
if (argZ == null) {
return ErrorUnspecifiedZ;
}
statement;
statement;
return Success;
} Today, this is accepted by most other programmers, at the method level, although the majority would like to add 'else's, including for the successful part. Sequences of 'else if' are by most not considered a new nesting level and usually accepted as a series of alternatives, although they strictly are not, by the grammar definition, of most C class languages.
A similar situation can occur in the middle of a method body: Several conditions must be satisfied for some operation to be performed. The C class of languages doesn't allow you to define arbitrary blocks (and certainly not to name them for the purpose of skipping out), so we have to 'abuse' e.g. a do statement:
do {
if (argX > MaxXvalue) {
break;
}
if (argY < 0.0) {
break;
}
if (argZ == null {
break;
}
statement;
statement;
}
while (false); I really would like to drop the 'while (false)'; (and preferably the introducing 'do' as well), but the compiler won't let me.
The 'classical' style, argued by some who consider themselves structural purists; insist that there shall be a single exit from every method; returning as soon as you discover a fatal error is messy coding, and the proper layout is like:
do {
if (argX <= MaxXvalue) {
if (argY >= 0.0) {
if (argZ != null) {
statement;
statement;
}
}
}
while (false); What really upsets people is if I want to get rid of the two first indentations as well, formatting it like
do {
if (argX > MaxXvalue) break;
if (argY < 0) break;
if (argZ == null) break;
statement;
statement;
}
while (false); It is my honest opinion that this code is far more readable than the fully structured purist code. I know of programmers who 'admit' that they agree about the readability. Yet, they will not accept this coding style; it is not 'proper'. So I reserve it for my private code that will never be handled by others.
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|