Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My C++ teacher once told me that if I have to use a break to get out of a loop I didn't think enough about the loop condition.
So did she (very good teacher btw) just fail to mention that foreach loops are an exception to this rule (which I have generally found to be true) or is there indeed a way to get out of a foreach loop without using a break?
I am asking in general, but most interesting for me would be for Java or PHP.
Edit:
In case I haven't made this clear, I am wondering if there is a way to get out of a foreach-loop without using a break. Not sure what this whole commotion is about, what's wrong with that question?
foreach loops don't have any exit condition except for the implicit "when there are no more items to iterate over", so it is not possible to break out of them early while avoiding break without using some sort of a terrible hack (e.g. throwing exception, modifying the iterated collection, setting a boolean flag dontContinue and checking it in each iteration, etc.).
For ordinary loops, there indeed always is an obvious way to avoid using break (stop the current iteration using continue or if, and put the early exit condition into loop's condition), however whether such approach leads to a more readable code than using break is disputable.
In some cases, the reason for you to want to break out of a loop early is because you finished whatever task needed to be done, or found the needed item. In such cases, consider putting the particular functionality into a separate method and using return instead of break.
Related
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 3 months ago.
Improve this question
Should I focus on trying to change every loop in my project to new Streams ? Should the loop below change to streams and how?
while(characterAfterEncryption > 122) {
characterAfterEncryption -= 26;
}
Trying to avoid using Traditional loops in Java 8.
Unable to find a way how to do it using Streams?
Use streams if and only if the stream-based code is easier to understand than the loop-based code. Streams and loops are both valid Java constructs, and it's the developer's responsibility to decide which one to use.
Streams are designed to support cases where you want to operate on multiple input values, e.g. from lists or sets or other series of data. And this does not apply to your snippet: you have a single input value. So, while it might be possible to create some piece of code that replicates the iterative algorithm using the streams API, the result will surely be very hard to read.
So, forget about "Trying to avoid using Traditional loops in Java 8". There are cases where this is a good idea, but also cases where the traditional loop is exactly the right thing to do. And if you ever tried to debug a streams expression, you'll be even more hesitant to use the streams API.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have searched this particular question a lot but didn't find any appropriate answers for it. Everywhere it's only written just only about when fall through happens , they haven't described my issue. Can anyone pls help me .
As we all know that switch case goes to fall through condition if there is no break statement. But i wanna ask that if switch case check value by cases then , if suppose it is checking the second case and there is no break in the second case , then according to language protocols it must falls through but as switch checks and compare the cases then why shouldn't the compiler again checks the next case , i mean then why it runs the block of next case without checking the case equality.
I think this question is pretty interesting.
Comparison for equality is done only once, until the execution flow enters a case.
A break is not necessary because it allows to control the execution flow.
There are a lot of situations with switch/case when you'd like to execute case B and after that you'd like to execute all following cases (case C, case D, etc).
So, this limitation is by design.
Actually it's not a limitation.
It gives you some flexibility in using this statement.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was asked this question in an interview.Please provide the solution if you know about this thing.Is there any difference between
for(int i=0;i<=N;i++)
and
for(int i=N;i>=0;i--)
which runs faster and why?
PS: Please differentiate on the basis of performance and the way compiler takes it.I am not asking about the basic difference between postfix and prefix notation.
I think this has the potential to become a better question, if we had more info. You should specify what language you are referring to. If this is JavaScript or something else then you need to mention that.
Secondly, consider revising your question. I suggest asking under which situations one is more appropriate than the other.
Whatever the language, the difference between the two is a stark contrast. The first for-loop involves incrementing a variable until a maximum value is reached (metaphorically-speaking, kind of like a race to the top), while the second involves decrementing a variable until a certain minimum is reached (like a race to the bottom).
Incidentally, in some languages, such as PHP performance is faster in a loop increment expression if you write the increment or decrement operators on the left instead of on the right.
This is an excellent interview question because any answer you give is likely to be wrong and more importantly be something you never previously thought seriously about.
The whole point is to throw you off your game. They want to see how you react when you're pushed into an area that you feel like you should be expert in yet find something about which you are not. Knowing the perfect answer to this question doesn't help you because they'll have 12 more questions lined up to throw you off.
What they want is to see how you respond to this situation. Do you make stuff up? Do you think about it carefully? Can you justify why it's not an important concern? Do you insist your way of looking at it is the only valid way? Do you listen when told of another way? Are you a pain to deal with if told to do it another way?
They will care so much more about the answers to this than whether or not you can save them a CPU clock tick.
But if it turns out you are an expert in this one dusty arcane corner you might earn a point.
If that is your real question then it's a duplicate of this question: Which of these pieces of code is faster in Java?
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 8 years ago.
Improve this question
I've been running through a lot of code reviews and keep running into a situation where I see conflicting coding standards regarding boolean variables and if statements.
Here is an example of one method(1):
boolean isXTrue = getBooleanValue(DataSetX);
if (isXTrue) {
//do code
}
Here is an example of the other method(2):
if (getBooleanValue(DataSetX)) {
//do code
}
Both do the same thing and function just fine. In some cases, method 1 is a lot more readable since the boolean variable can be named something meaningful, while method 2 saves more lines and unnecessary boolean variable creations.
Maybe I am reading too deep into a simple coding standard, but I'm rather curious that if we use method 1 more often, we could have unnecessary booleans being made.
Sorry if this is a stupid question, but I wanted to get some opinions anyway :)
It's likely that the compiler will optimize both cases so that either way is identical at run time. Of course, that depends on code outside the context that you've provided.
As for the question at large: it's something that you and your coworkers or group need to come to a consensus about. If you're looking for a definite answer about which one to choose, I don't think you're going to get anything convincing other than personal preferences of readability vs line count.
Discuss this with the others that maintain your code base and decide on which should be preferred. Clearly explain why. Then move on to more...err...important issues.
As for my preference? I like option 1. To me, it's more readable, the variable name can be something descriptive like isActive, which makes the code easier to read. Also, inspecting values during debugging is probably easier as you have a definite variable with which to reference prior to its use later in the chain. Again, that's my preference.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've heard that you shouldn't use foreach loop where you can avoid it because it can cause thread concurrency, what does it mean thread concurrency, and is it true ?
So when should you use the for-each loop?
Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel.
These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
Emphasis mine.
Unless you clear up what you mean with exactly, this would indicate that you're wrong.
Using a for each loop when altering a collection can trigger it to incorrectly detect a concurrent modification which looks like it has been modified by another thread when in fact it has been modified by the same thread.
"for each" doesn't have anything to do with concurrency. You can find the ConcurrentModicationException a number of way, one is to use Iterator.remove().