while reading "Java complete reference seventh edition" in page 100.
I read this statement "However, be careful. Too many break statements have the tendency to destructure your code"
What I don't understand how can break statement change or deconstructed in my code?
Is that in java only or in all programming languages?
Is that something linked to byte-code?
Thanx so much, please do not misunderstand me :)
Too many break statements have the tendency to destructure your code
I believe that the author means that it is more difficult to follow the execution paths in your code. This is because break jumps to a line of your code that potentially can be far away from the line with the break.
The author uses the word de-structure your code. Its just an expression. what he actually meant by that is:
Imagine you writing five loops one inside another having break statements for all the loops. If the loop gets bigger and bigger, there are high chances of losing the execution path as a developer i.e. which loop is being executed and from which loop the control has broken out of.
Imagine the chaos it creates if you have more loops having break for each loop/more break statements for a few loops. The only thing that catches your eye is the break statement .
However, be careful. Too many break statements have the tendency to destructure your code.
This doesn't mean that if you have a switch statement to compare over 100 unique values, then it will de-structure your code. Because, in this case, that's the only need.
But suppose, you are using too many loops, could be anything, for-loop, while-loop, do-while-loop or even if-else conditions, excessively using breakstatement will come out with too many permutations and combinations of execution path which we at development phase might not see. And then, can cause a big trouble at real time execution with multiple values or multiple types of values which may trigger a new, unexplored path of execution. (I mean, those paths, which we were not intended to create.)
So, the author says better to avoid too many break statements. Not all.
Related
Why using labels in Java is a bad practice? I cant find a reason. All explanations - you shouldn't use it just because you shouldn't.
It's difficult to read code containing breaks to a label. Also, a label can be accidentally moved, or code inserted at an incorrect location with respect to a label. The compiler is not able to warn you of these effects since the code remains syntactically valid.
Code that's difficult to read is difficult to maintain. Bugs will inevitably creep in.
Other control structures (break, continue, while, for, etc.) don't suffer from this.
Note that a switch to a label doesn't suffer from these effects either: the structure of a switch block is well-defined.
The most sensible alternative to breaking out of a nested loop is to recast the code to a function and use return. You also get the added benefit of being able (potentially) to return a value back to the caller.
I think that you are referring to break and continue labeled.
The problem is that labeled break (and continue) is a construct of imperative languages that is absolutely not related to Object Oriented.
In Object Oriented programs the flows can be easily understood. It is not possible to jump from a part of code to another part of code, you can only call a method or continue current code or exit the current block of code.
Jumping from position to position is a probable point of break for your application where bugs can easily happens. Jumping creates what is called spaghetti code
Labelled breaks (and breaks, in a smaller way) are a more-modern equivalent to the old GOTO statements of older languages (FORTRAN, COBOL, Basic). Goto statements were found to be much more liable to contain an error than all other kinds of statements combined -- the study I'm remembering measured it as 9 times more likely. This gave rise to the "structured programming" movement in the 70s, and the banning of the goto statement from some software shops at the time.
It is more important to be able to read code easily than to be able to write it without restrictions.
Labels are fine to break out of nested for-loops. I'd suggest to put the nested loops in a separate method and then break out with return.
The problem is that the complex flows of processing becomes really hard to follow.
I've just read about spaghetti code ( wiki link) that "goto" statement creates, I wonder if label in java makes spaghetti code?
I just interested in this because one of my old question about break and label in java that I asked here
Labels are so rarely needed/used that no, not really. Also you can't jump to a label, you need to break to it, so you can't get the similar kind of confusion as with filling the code with goto whereever statements.
The main problem with labels is that they are rarely used which means they are surprising and possibly confusing for a reader. e.g
http://stackoverflow.com/
System.out.println("Hello SO");
At first glance, that doesn't even look like valid Java code, but it is.
Because labels tend to be used only when the are really needed, and sometime not used when they should have been used IMHO, they don't lead to spaghetti code in Java in reality.
inside my java programm I need to have a control-structure which should give 3 different outcomes to 3 different inputs.
Input 1: Text 1
Input 2: Text 2
Input 3: Text 3
My Question here is: Best-Practice wise and efficiency wise, which control structure should be used? My First thought has been a switch case, but why would I choose that over IF-Structures or nested ? operators??
I think you'll find it generally agreed that the switch statement is mildly preferred in this situation, purely on the basis of readability. It scales a lot better if additional cases are added and even with three options, it's still a bit more readable, particularly with the cases being simply three variations of one input. Performance differences are negligible but there are surely discussions out there if you really want to get into that specific aspect.
I'd suggest avoiding the ternary operator (i.e., inline if/'?') for any more than two cases for similar reasons of readability. Personally, I don't parse it as well and I avoid it unless all expressions involved are very brief.
Mostly off-topic, but interestingly, switching on Strings wasn't added to Java til Java 7.
you should strive for good readability first, then for efficiency if required. If there are many options, use switch if small, use if/else
Maybe a nested ternary operator? Just kidding. I think efficiency here is going to be almost identical whatever structure is used. I would go for the if/else because I think is more readable than a swtich (an less error prone -don't forget the breaks-) but it's just an opinion.
Is there a loop in java that executes multiple methods (or multiple actions) at the same time?
Example:
replace(line1, line2);
replace(line3, line4);
replace(line5, line6);
replace(line7, line8);
replace(line9, line10);
Loop through a file and replace the strings - they aren't in order.
Regarding this code in your question's edit:
replace(line1, line2);
replace(line3, line4);
replace(line5, line6);
replace(line7, line8);
replace(line9, line10);
You simply need one method, replace, called by a for or while loop (depending if you know in advance how many times you'll loop). If this doesn't solve your problem, then (again), please ask a better and clearer question.
There's no need to use threads to do these all at the same time. You state that "I only need to do this once", perhaps, but you need to call replace at least 5 times in this example, so actually a loop that calls replace 5 times passing in different parameters would work nicely. If you had an array of pairs of lines, you could loop through the array with a for loop calling replace as you loop. Again there's no need for a "do together" here but rather a "do in order".
But again you seem to be withholding critical information for unknown reasons. Again, I urge you to study this link: How To Ask Questions The Smart Way
When developing for Android is a switch statement more efficient than an if-else chain? A switch statement takes more lines of code, but looking at anecdotal evidence seems to be the more commonly used in Android applications.
The examples below illustrate the same programming construct with a case statement and if-else chain. The switch statement requires 10 lines while the if-else chain requires 7.
Case Statement
public void onClickWithSwitch(View v) {
switch(v.getId()) {
case R.id.buttonA:
buttonA();
break;
case R.id.buttonB:
buttonB();
break;
case R.id.buttonC:
buttonC();
}
}
If-else chain
public void onClickWithIf(View v) {
int id = v.getId();
if(id == R.id.buttonA)
buttonA();
else if (id == R.id.buttonB)
buttonB();
else if (id == R.id.buttonC)
buttonC();
}
Why would switch be more common than an if-else chain? Do switch statements offer better performance when compared to if-else chains?
The reason languages have switch statements is to allow the compiler to generate a jump table, which is fast if it's large, because at run-time it can get to the desired code in O(1) rather than O(N) time.
It's only helpful speed-wise if there are many cases and the code to execute in each case does not take much time, and the program spends much percentage of time in this code at all.
Other than that it's purely a matter of taste.
There is no relationship between number of code lines and speed. What matters is the kind of assembly language code that's generated, which I'd encourage you to get familiar with.
Unless your sequence of ifs/cases is truly vast, I don't think it matters. With the switch statement, it's more clear what's going on. The only downside is all the break statements and the potential to miss one, but a static analyzer should catch that.
Best would be a map keyed by the id or some clever use of subclassing
"More efficient" is a vague concept, because there are so many ways to measure it. I suppose most people think of execution time. On the other hand, most people don't think of memory efficiency. A switch statement with widely spaced test values can be a horrible memory hog, unless the compiler is smart enough to re-interpret it as an if-else chain.
There's a lot to be said, as well, for programming efficiency, including maintenance and readability. As sblundy noted, a switch statement can be clearer about the programmer's intent than an if-else chain. Comments can counterbalance that, but that requires more work for the programmer and there's also the risk that the comments and code don't match (particularly after a few maintenance cycles).
I imagine that most people follow whatever style they have been taught (or told to follow), without thinking about it too much. The rest of the time, I think most decisions about switch vs. if-else are based on which one best matches the programmer's thinking at the moment the code is being generated.
You asked: Is a switch statement really more efficient?
Anybody claiming to have a definitive and general answer on this question, talks nonsense. There is exactly one way to find out which is faster in your case: Use a proper micro-benchmarking framework on your target plattform with your complete software, not a simplified example. If that reveals a measurable and statistically signifanct difference I'd be interested in hearing about it. I doubt you'll find any measurable difference for a real program.
Therefore, I would strictly go for readability.
While we're on the subject, nobody mentioned that you should always have a default line in switch statement. Usually you want to throw an exception, but at least you should assert and/or log the error.
This is just good basic defensive programming. It alerts you that you have a programming error if you later add another button (in this case).