Ok, this is a hard question for me to ask, to make you udnerstand what I want to know
So assume this pseudo code :
While(true)
if(boolean is true)
else
End While
Ok, with this, I have a while who,s always running, what I wonder is if there's anyway to enter the if without re valuating the boolean each time, also you need to know the boolean may change but never in the if itself.
I know it seems crazy thinking, I just wonder if it's possible to enter a condition without evaluating it, IF the condition was true the time before.
EDIT
Also I'm imaginating this idea from an electric cicuit, imagine a switch if the contact is made the electricity will go straith to the light else it woN't pass but it doN,t really check wich way it just assume where he can go, I know I,m really confusing :S
EDIT 2
Maybe this will be more clear ? i'm not sure
No, because what you're asking for is "how do I branch without checking a condition?" and the answer is, you can't.
If the condition check is a complex operation then You can memorize the result of a condition check in a boolean variable, and branch on the variable.
However, in order to truely eliminate the branch in your example, the general pattern is to separate the true and false conditions to be outside the while loop:
while(true)
{
if(condition) break;
}
while(true)
{
// condition was true
}
Simple, just simply emit the if statement if you want it to pass its condition automatically.
Related
Scenario: my query variable is dynamic, there are 4 possible values for that depending on the report type (_reportType). Meaning there are 4 different queries and some of it doesn't have #STAFF in the where condition, so my question is, is it safe to just leave my
dBCommand.AddParameter("#STAFF", staff)
there or should I include if else condition just to be safe?
Like this
if(_reportType == 1)
{
dBCommand.AddParameter("#STAFF", staff);
}
else if (_reportType == 2)
{
//code
}
else if (_reportType == 3)
{
//code
}
else
{
//Don't add dBCommand.AddParameter("#STAFF", staff);
}
Is it safe just to leave addParameter("#STAFF", staff) even though I'm not going to use it in a query?
Example I'm going to write
dBCommand.Initialize(string.Format(query, "RetailTable"), batch);
dBCommand.AddParameter("#STAFF", staff);
But the query value doesn't have #STAFF in the WHERE condition
It should generally be ok to specify unused parameters, aside from the minor overhead of sending the value to the server. The exception is if you execute DDL queries that have a restriction of being the only statement in the batch (e.g. CREATE VIEW). Those would fail due to the parameter.
There are 2 glaring bad practices in your approach:
1. Generating dynamic query within the code.
This approach has many drawbacks and possible security loopholes. You should almost always avoid doing that.
Please go through the following links to understand this more:
https://codingsight.com/dynamic-sql-vs-stored-procedure/
https://www.ecanarys.com/Blogs/ArticleID/112/SQL-injection-attack-and-prevention-using-stored-procedure
2. Trying to use generic Where Clause that fits all your variations.
This approach is disaster in waiting, regardless of the query being written in your application code OR in a Stored Procedure.
This is an ugly code-smell and a maintenance nightmare.
No developer can ever be 100% sure that there will not be any change required during the lifespan of the application due to a simple fact that the client WILL need enhancements on regular bases.
So, even if this approach may work for you for a small period of time, this will blow back.
Assume, over the period, there are few more filter parameters added due to new requirements. Now, imagine how your code would look like and the possibilities it creates of problems you may get if they are not handled properly. Specially when YOU are not making those changes. Scary, right?
Always write code that will not only be easier to read and understand, but also easy to enhance and maintain, regardless of the person writing the code.
So, IMHO, you should add those if-else conditions OR use switch-case blocks to safeguard yourself and your client. It may look overkill in the start, but will surely payoff in future.
Hope this help!
Can I switch a boolean with one statement as effectively as with an if/then/else ?
Found this in another piece of code that is going into my app...
private void whatever()
{
////
//// a bunch of stuff
////
if (SomeBooleanValue)
{
SomeBooleanValue= false;
}
else
{
SomeBooleanValue = true;
}
}
Out of curiosity, I tried this...
private void whatever_whatever()
{
////
//// the same stuff
////
SomeBooleanValue = !SomeBooleanValue;
}
...and walked through it in debug, and it appears that I get the same result.
Is there a good reason to use the if/then/else instead of the single line way ?
Is there a good reason to use the if/then/else instead of the single line way
Not any that I can think of. Using the ! operator is cleaner and more intuitive for most programmers.
The 1-line way is perfectly fine, and the only reason why you'd use the if/ else structure is if you were doing other things aside from just toggling the boolean.
I would say the second one is better since it is more readable and compact (if/then/else IMO just adds unnecesary lines of code), that would be the only (but strong!) reason to prefer one from the other
Due to compiler optimizations, it will be the same as using the ! operator, which is easier to read for other programmers.
However,
To improve performance, the CPU will try to predict the execution logic ahead of time. For conditional (if/else) statements, it will try to predict the result of the condition and then load the rest of the logic. If it chooses incorrectly, it must go back and re-calculate everything again, hence decreasing performance.
http://en.wikipedia.org/wiki/Branch_predictor
Please, please, please write the code as a negation; it is the most succinct and concise expression of intent. If you write the code the first way, every reader of your code is going to waste time wondering why you did NOT write the simple negation.
Most code will be read, by you and others, many more times than it is written. Writing code that eases the reading process is, almost by definition, good code.
Yes, I know the wording is hard to understand, but this is something that bugs me a lot. On a recent project, I have a function that recurses, and there are a number of conditions that would cause it to stop recursing (at the moment three). Which of the situations would be optional? (I.E. best performance or easiest maintenance).
1) Conditional return:
void myRecursingFunction (int i, int j){
if (conditionThatWouldStopRecursing) return;
if (anotherConditionThatWouldStopRecursing) return;
if (thirdConditionThatWouldStopRecursing) return;
doSomeCodeHere();
myRecursingFunction(i + 1, j);
myRecursingFunction(i, j + 1);
}
2) Wrap the whole thing in an if statement
void myRecursingFunction (int i, int j){
if (
!conditionThatWouldStopRecursing &&
!anotherConditionThatWouldStopRecursing &&
!thirdConditionThatWouldStopRecursing
){
doSomeCodeHere();
myRecursingFunction(i + 1, j);
myRecursingFunction(i, j + 1);
}
}
3) You're doing it wrong noob, no sane algorithm would ever use recursion.
Both of those approaches should result in the same IL code behind the scenes since they are equivalent boolean expressions. Note that each termination condition will be evaluated in the order you write it (since the compiler can't tell which is most likely), so you will want to put the most common termination condition first.
Even though structured programming dictates the second approach is better, personally I prefer to code return conditions as a separate block at the top of the recursive method. I find that easier to read and follow (though I am not a fan of returns in random areas of the method body).
I would opt for the first solution, since this makes it perfectly clear what the conditions are to stop the recursion.
It is more readable and more maintainable imho.
If it's something that needs to be fast, I'd recommend hitting the most common case as quickly as possible (i.e. put the base case at the end because you'll only hit it once). Also think about putting a base case-1 before the recursing clause (i.e. perform the test before you call the function again rather than check it on entry to the subsequent call) if that will make a difference.
And, with all things, don't optimise unless it's a problem. I'd go for clarity first.
I like the variant 1 better...
It is much easier to read then variant 2. Here you have to understand 3 negations and chain them all together with and. I know its not "hard", but it takes much longer then glancing on variant 1
My vote is for option #1 as well. It looks clearer to me.
I have a couple of methods that return a bool depending on their success, is there anything wrong with calling those methods inside of the IF() ?
//&& makes sure that Method2() will only get called if Method1() returned true, use & to call both methods
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
Method2() doesn't need to fire if Method1() returns FALSE.
Let me know there's any problem with the code above.
thank you.
EDIT: since there was nothing wrong with the code, I'll accept the most informative answer ... added the comment to solve the "newbie & &&" issue
I'll throw in that you can use the & operator (as opposed to &&) to guarantee that both methods are called even if the left-hand side is false, if for some reason in the future you wish to avoid short-circuiting.
The inverse works for the | operator, where even if the left-hand condition evaluates to true, the right-hand condition will be evaluated as well.
No, there is nothing wrong with method calls in the if condition. Actually, that can be a great way to make your code more readable!
For instance, it's a lot cleaner to write:
private bool AllActive()
{
return x.IsActive && y.IsActive && z.IsActive;
}
if(AllActive())
{
//do stuff
}
than:
if(x.IsActive && y.IsActive && z.IsActive)
{
//do stuff
}
As useful as they are, sequence points can be confusing. Unless you really understand that, it is not clear that Method2() might not get called at all. If on the other hand you needed BOTH methods to be called AND they had to return true, what would you write? You could go with
bool result1 = Method1();
bool result2 = Method2();
if (result1 && result2)
{
}
or you could go with
if (Method1())
if (Method2())
{
}
So I guess the answer to you question IMHO is, no, it's not exactly clear what you mean even though the behavior will be what you describe.
I would only recommend it if the methods are pure (side-effect-free) functions.
While, as everyone says, there's nothing "wrong" with doing things this way, and in many cases you're doing precisely what the language was designed for.
Bear in mind, however, that for maintainabilities sake, if Method2 has side effects (that is, it changes somethings state) it may not be obvious that this function is not being called (a good programmer will usually know, but even good programmers sometimes have brain farts).
If the short circuited expression has some kind of side effect, it may be more readable to seperate the statements, strictly from a maintenance perspective.
Looks good to me, multiple clauses in the if() block will short circuit if an earlier condition fails.
There shouldn't be any problem.
The normal behavior is that Method1() will execute, and if that returns true Method2() will execute, and depending on what Method2() returns, you may / may not enter the if() statement.
Now, this assumes that the compiler generates code that executes that way. If you want to be absolutely sure that Method2() doesn't execute unless Method1() returns true you could write it like this
if( Method1() )
{
if( Method2() )
{
// do stuff if both methods returned TRUE
}
}
But, I've always observed that your code will run as expected, so this is probably not necessary.
Nothin' wrong.
Actually...I wouldn't name them Method1 and Method2. Something more descriptive. Maybe passive sounding too (like StuffHasHappened or DataHasLoaded)
Looks good to me, but there are some caveats... This is NOT the kind of thing where blanket rules apply.
My guidelines are:
If the method names are short, and there are not too many of them, then it's all good.
If you have too many statements/method calls inside the if statement, you most likely are comparing more than one "set" of things. Break those "sets" out and introduce temporary variables.
"Too many" is subjective, but usually more than around 3
When I say "method names are short" I'm talking not just about the names, but the parameters they take as well. Basically the effort required for someone to read it. For example if( Open(host) ) is shorter than if( WeCouldConnectToTheServer ). The total size of all these items is what it comes down to.
Personally, I would consider
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
to be a bad practice. Yes, it works in the current environment, but so does
if(Method1())
{
if (Method2())
{
// do stuff if both methods returned TRUE
}
}
But will it work in ALL environments? Will future, possibly non-Microsoft, C# compilers work this way? What if your next job involves another language where both methods will always be called? I wouldn't rely on that particular construct not because it's wrong, but because it doesn't solve any serious problem, and it may become wrong in the future
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Switch(some case) {
case 1:
// compute something ...
return something;
break;
case 2:
// compute something ...
return something;
break;
/* some more cases ... */
case X:
// compute something ...
return something;
break;
default:
// do something
return something;
break;
}
In my opinion:
Assuming this switch statement is justifiable, the return and break just doesnt look right or feel right.
The break is obviously redundant, but is omission poor style (or is this poor style to begin with?) ?
I personally dont do this, but there is some of this in the codebase at work. And no, im not going to be self-righteous and correct the codebase.
No, omission is not poor style - inclusion is poor style. Those are unreachable statements. Get rid of them.
I like the fact that the cases return directly instead of setting a local variable and then returning just at the bottom - it means that it's incredibly clear when you're reading the code that it does just need to return, and that's all.
Side-note in terms of switching in the first place:
As for whether using a switch statement is the right thing to do here, it really depends on other things. Would it make sense to use a polymorphic type instead? If you're in Java, could you use a smart enum? (You can mimic these in C#, but there isn't as much support.)
I'd say this should at least prompt considering different designs - but it may well be the simplest way to do what you want.
The C# Compiler gives a warning if you do this saying that the break is unreachable code. So in my book it is bad form to have both return and break.
In my opinion, I would omit the 'break' keyword. I personally think it helps remind people that 'Execution has ended! Nothing more to see here!'.
I would make a small change:
switch(some case) {
case 1:
// compute something ...
break;
case 2:
// compute something ...
break;
/* some more cases ... */
case X:
// compute something ...
break;
default:
// do something
break;
}
return something;
I'm not sure how literal that code is intended to be so some of these observations may not be applicable...
"case 1"
If you're truly hard-coding numers like this I think it is poor style and you should look into using an enumeration.
If you are simply returning something and there is no additional logic in a subset of the cases, you might consider putting the "somethings" in an array or dictionary and simply addressing them by their index rather than using a switch statement...
return somethings[index]
Code smell implies a design problem. This is just an issue of formatting. I think most people would agree that a version with breaks omitted is superior.
The break is redundant.
Some rule of thumb, It is always good to exit a function in one place only, But since this rule was made Try-Catch was invented (oop goto).
If you keep the same style all over your application, I guess you can live with the return in the switch.
The code smell here is the hard coded values in the case statements.
As for the returns it is more a question of taste and good judgement. Sure if your case spans mutiple pages it is easier to read if the return is in the case, but then the problem is the big switch to begin with.
Personnaly I prefer the single return option because if ever you need to add some more processing then it is cheaper to refactor than visiting all the cases. Also, if given to someone else to refactor they will not have the temptation to copy paste the code in every case, least I would hope so ... if they do they better hope I am not the one doing their code review (for the copy paste obviously).
Switch statements are themselves a code smell.
Along the lines of what l99057j said, if all you're doing is mapping inputs to constant values, this is a place for an appropriate lookup structure, such as an array/list for sequential inputs or a dictionary/map for a sparse one, not a switch statement. If you're calculating something, then the value would be a delegate that you call with the input.
Others have commented on other aspects. As for the breaks that are redundant after the returns: I would KEEP them, along the same reasoning as { } around a single-statement if body: it should be second nature for every programmer to put those braks there. Better have 100's of such redundant breaks than one unintentionally missing.