Why actually the fall through happens [closed] - java

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.

Related

Test an if condition with mockito [closed]

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 3 years ago.
Improve this question
Code of the if statement:
if (reponse.getStatus() >= HttpServletResponse.SC_BAD_REQUEST) {
LOGGER.error("Erreur lors de l'enregistrement de la trace technique - {}", reponse.getStatusInfo().getReasonPhrase());
}
Basically testing always consists of two parts:
preparing some input, so that your production code under test takes a specific path
verifying that the expected "things" happened
First one is easy: you have to somehow make sure that the response object that your production code is dealing with has the required status. How you do that, very much depends on context.
For the second aspect, that is probably hard. You see, the only action taking place is a (probably static) call to that error() message. If that is the case, then your only way of testing this would be to use JMockit or PowerMock(ito), because those two frameworks allow you to verify static method calls.
So, the real answer is:
figure for yourself how you can gain control over that response object
buy into using one of these mocking frameworks (not recommended)
rework your code so that it becomes testable without adding that (imho really really bad) dependency towards PowerMock(ito).

why switch or if else statement is not considered polymorphic? [closed]

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 4 years ago.
Improve this question
Every answer on stack overflow provides information on how to replace switch or if else with polymorphism but
the switch, if else constructs also help in providing different behavior of an object with respect to context and inputs.
Why if else,switch is not considered as a part of polymorphism.
Conditional becomes a code smell when we have to check an object’s type in order to make some logic or behavior decision. It doesn’t matter whether it is a stack of if/else block or a switch statement.This violates open-closed principle.
The open closed principle states that the entities(classes, modules, functions etc) should be open for extension,but closed for modification.Which means that these entities won't be allowed to make changes in its source code.
This can be achieved through Abstraction and Polymorphism.
Benifits of Polymorphism over Conditionals
instead of asking an object about its state and then performing actions based on this, it is much easier to simply tell the object what it needs to do and let it decide for itself how to do that.
Removes duplicate code. You get rid of many almost identical conditionals.
If you need to add a new execution variant, all you need to do is add a new subclass without touching the existing code (Open/Closed Principle).
Polymorphism in a concept that allows an Object to retain behavior and properties from its parent classes. Explained further here and here
if, else and switch are procedural code constructs.
The two have nothing in common.
Edit: Thanks #Ted Hopp, correcting my post.

Get out of a foreach [closed]

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.

Difference between i++ and i-- [closed]

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?

JAVA: Create boolean variable or put argument within If statement? [closed]

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.

Categories

Resources