I watched weird situation: I didn't get any error when used something like this in my Android app code:
#Override
public void onBackPressed() {
if (getActionBar().getSelectedTab().getPosition()==1)**;**
{
if ( getFragmentManager().findFragmentByTag("Tag B") instanceof ContactsArchiveFragment)
{
final ContactsArchiveFragment fragment = (ContactsArchiveFragment) getFragmentManager().findFragmentByTag("Tag B");
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
Log.i("calls act back cont archive", "on back clicked");
super.onBackPressed();
}
}
}
}
When I tried to do something like this:
#Override
public void onBackPressed() {
if (getActionBar().getSelectedTab().getPosition()==1);
{
if ( getFragmentManager().findFragmentByTag("Tag B") instanceof ContactsArchiveFragment)
{
final ContactsArchiveFragment fragment = (ContactsArchiveFragment) getFragmentManager().findFragmentByTag("Tag B");
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
Log.i("calls act back cont archive", "on back clicked");
super.onBackPressed();
}
}
}
else
{
}
}
I received Syntax error on token "else", delete this token. When I saw the semi, I reliazed what is the problem. But this wondered me, can someone explain what it is about?
But this wondered me, can someone explain what it is about?
Sure - the ; is just an empty statement, and it's fine to have a block with no if. For example, this is valid:
if (i == 0)
System.out.println("i was 0");
System.out.println("In top-level block");
{
System.out.println("In a block");
}
... and the semi-colon after the if is just equivalent to the first if statement with an empty body.
Personally I always use braces for if statements (and while statements etc). Some compilers (e.g. the one built into Eclipse) allow you to trip a warning or error if you use an empty statement like this.
The else form isn't valid because you can only have an else clause as part of an if/else statement, whereas the if statement is already "done" at the end of the semi-colon.
When you have just an if like that:
if();
{
// Supposed to be with if
}
the block that was supposed to be with if, is now just a local block independent of if. The if statement ends at the semi-colon. Compiler wouldn't mark it as error, as it is perfectly a valid code.
Now with your 2nd case:
if ();
{
} else {
}
Note that the if statement has ended at semi-colon only, and then you have a block. But the else there is not coming just after any if as it is required to come. So, it is really an else without an if.
This is similar to the case when you will get an error in this code:
if () {
}
System.out.println("Hello");
else { // Error. Which `if` block do you suppose else to be bound with?
}
It's just that, the above case is quite obvious on first look. So it goes like:
if ();
can be visualized as:
if()
; // Empty statement
which is equivalent to an empty if block - if() { }
An extra ; causing all the mess here.
That semicolon terminates the statement there ,And assuming it as a new block stating from there.
If you see closely
if (getActionBar().getSelectedTab().getPosition()==1); <----
That is a statement,Not an If condtion.
condition should be
if (getActionBar().getSelectedTab().getPosition()==1){
}
Remove that extra ;
If you see the docs related to blocks,
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
Related
I just need to know that if you do an else if on two lines does it still perform the same as an else if on one line?
a bunch of ifs then.....
else if(somecondition here) {
//do some stuff here
}
does the below code perform the same as above?
else
if(somecondition here) {
//do some stuff here
}
OR does it perform as an ELSE by itself then goes into the if after all else, like a normal else statement would.
Whitespace doesn't matter in Java, as long as you have at least one. So the two snippets are equivalent.
Even if you write
else if (...)
or
else
if (...)
it will still be the same.
OR does it perform as an ELSE by itself then goes into the if after all else, like a normal else statement would.
No, here the if statement is technically inside the else clause. If you want the above behaviour, try putting a ; after else. This makes the if not part of the else clause.
if (...) {
} else; // note the semicolon
if (...) {
}
But you'll never write that anyway, you'll just remove the else altogether.
else if(somecondition here) {
//do some stuff here
}
and
else
if(somecondition here) {
//do some stuff here
}
both are same. Java doesn't use newline to determine new statement
If you want the else to be itself and if to be in it you should change it to-
else {
if(somecondition here) {
//do some stuff here
}
}
Technically it is same as else if in some cases
This question already has answers here:
Difference between Return and Break statements
(14 answers)
Closed 5 years ago.
I'm studing a code wich has this code:
public void add(StockUpdate newStockUpdate) {
for (StockUpdate stockUpdate : data) {
if (stockUpdate.getStockSymbol().equals(newStockUpdate.getStockSymbol())) {
if (stockUpdate.getPrice().equals(newStockUpdate.getPrice())) {
return;
}
break;
}
}
/* data.add mathod checks the new data against the existing data. If no change is found, the update is discarded. */
this.data.add(0, newStockUpdate);
notifyItemInserted(0);
}
I just want to know if the return and the break statements in this code are, in any way, different from each other. Because I tested a similar example outside this code and both return and break stopped the loop and terminates the function.
break stops just the loop; return stops the entire method.
The juxtaposition of break and return like this makes it quite hard to follow the logic of the add method. Consider that the following might be easier to follow:
public void add(StockUpdate newStockUpdate) {
StockUpdate stockUpdate = findStockUpdateBySymbol(newStockUpdate.getStockSymbol());
if (stockUpdate != null
&& stockUpdate.getPrice().equals(newStockUpdate.getPrice())) {
return;
}
/* data.add mathod checks the new data against the existing data. If no change is found, the update is discarded. */
this.data.add(0, newStockUpdate);
notifyItemInserted(0);
}
// On non-android, it's easier to do this with a stream/findFirst.
private StockUpdate findStockUpdateBySymbol(StockSymbol sym) {
for (StockUpdate stockUpdate : data) {
if (stockUpdate.getStockSymbol().equals(sym)) {
return stockUpdate;
}
}
return null;
}
I'd say that this is easier to follow (whilst being slightly more verbose) because it is separating out the different things that are being done: you're trying to find a matching stock symbol; and if you find that, do other stuff. Mixing that all together into the one loop obfuscates that intent.
Is it good or bad practice to have an else branch which only returns in a function that returns type void? Such as this code:
public void myFunc() {
if (<some condition>) {
//run some code
} else {
return;
}
}
Note that this topic is opinion based, you will probably see many different preferences from user to user.
For readability and maintainability you should try to reduce the complexity of your code. Therefore you want to also reduce the nesting. Thus my prefered variant would be:
public void myFunc() {
// Directly leave if condition does not hold
if (!condition) {
return;
}
// Now do the rest of the code
}
If you want to stick to your current variant then I would suggest to just drop the else part because it just aggravates the readability in my opinion, so:
public void myFunc() {
if (condition) {
// Do something
}
// You can always leave a comment if you think
// that helps a reader, so you can put "Do nothing
// if condition does not hold" here
}
However as said, I personally prefer the first variant because it reduces the nesting of the overall code.
No, this else statement is not required if you are not doing any operation.
The else statement is basically used to carry out an operation, if the condition of if do not met.The best practice is not to write the else statement, if you are not doing any operation.
public void myFunc() {
if (<some condition>) {
//call FunctionA();
} else {
//call FunctionB();
}
}
In the above case, the use of else is valid. But if you are not doing any operation, then the statement is useless. Please read Clean Code Book by Robert Cecil Martin. It will help you in writing clean code.
From the java.lang.Void class documentation:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
So any of the following would suffice:
Parameterizing with Object and returning new Object() or null.
Parameterizing with Void and returning null.
Parameterizing with a NullObject of yours.
You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.
I'm refactoring a very large method with a lot of repetition in it.
In the method there are many while loops which include:
if ( count > maxResults){
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
break;
I want to extract this as a method, because it happens 3 times in this one method currently, but when I do so I get an error on the break as it is no longer within a loop. The problem is that it is still necessary to break out of the while loops, but only when the maximum number of results are reached.
Any suggestions?
Suppose the method is :
public boolean test(int count, int maXResult) {
if ( count > maxResults) {
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
return true;
}
return false;
}
Call method from loop as :
while(testCondition) {
if (test(count, maxResults)) {
break;
}
}
This is impossible to do directly.
Most often you want to break because you have found the solution and no longer have to search. So indicate in the called function that there is/was success, for instance by returning a result or a boolean to indicate success. And if the function returns success, then break.
If it is now within a method instead of the while loop have it return a value and then break based on that.
i.e.
public bool refactoredMethod(parameters)
{
if ( count > maxResults){
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
return true;
}
return false;
}
Try to break the loop in the method using return;
As Thriler says you cant do it directly. You could extract part of it to the method and do something like:
if(isTooManyResults(count)) { break; }
Obviously your isTooManyResults method would need to return true if there are too many results and false otherwise
Let's say I had a lot of code between an if statement. Is it more proper to do a quick if-else check before it, and if it fails, return.
OR create the if statement with a lot of code in-between but not use return?
OR is it just a matter of preference?
so my 2 options are:
if(!something){
return
}
else
//lots of code here
if(something){
//lots of code here
}
From a performance perspective, you should always return from a function as quickly as you can, avoid doing unnecessary computations, "short-circuit" if you will. So checking for error cases and returning quickly would be the better policy.
Edit to add: In the same vein, you should always check the cases that are most likely to be violated first, this is sound advice when structuring your conditionals as well (|| and && checks)
I think this looks much nicer:
func() {
if(someCondition) {
return;
}
if(otherCondition) {
return;
}
//lots of code
}
than this:
func() {
if(someCondition) {
return;
} else if(otherCondition) {
return;
} else {
//lots of code
}
}
or this:
func() {
if(!someCondition) {
if(!otherCondition) {
//lots of code
}
}
}
It looks even uglier with more conditions, so I generally use the first method.
I prefer "shortcut". It has nothing to do with performance, as modern computer can handle if-else very fast, so we should focus on code readability.
However, if there's so many if-else in code, you may re-think your design. Refactory can be a better choice.
Readability and performance are not necessary conflicting constraints but when they are I tend to give readability the front seat.
To enhance readability I tend to follow the following rules.
Rule 1. Keep return as the last line of code, whatever comes in the middle. In other words don't sprinkle return statements whenever you want just because you're not too sure your if-else structure will cascade down just before the final return.
Except may be for the simplest methods I privilege a structure like
MyType func() {
MyType result ;
if ( condition ) {
result = result_1 ;
} else {
result = result_2 ;
}
return result ;
}
over an allegedly simpler
MyType func() {
if ( condition ) {
return result_1 ;
} else {
return result_2 ;
}
}
In my opinion the performance cost, if any, is negligible. However, when scaled up, I find the first coding pattern much more readable.
Rule 2. Refrain from starting a logic by "evacuating" error conditions, just in order to get them out of the way and free your mind. If your logic is well thought these checks will find their place in the logic (also have a look at guava for many well though techniques of encapsulating routine checks in helpers).
Many freshmen in my team start coding things like this
MyType func (ArgType arg1,...) {
if ( arg1 == null ) {
throw new Exception ( "hey dummy, we don't take null arg1) ;
// or return null ;
}
if ( arg2 == null ) {
// you got the picture...
}
// wow at last !!! all checks done
// Combine args and return result...
}
Which I have to say, is already a progress on just taking all conditions for granted
I tend to prefer
MyType func (ArgType arg1,...) {
MyType result ;
if ( try_to_compact_all_checks_here ) {
// Combine args and return result...
} else {
// throw, log, nullify result etc
}
return result ;
}
If the condition "try_to_compact_all_checks_here" does not fit in one line, I even sometimes prefer to get out of my way and I encapsulate all the checks in a private function. Even if it's called only once.
Rule 3. Keep the number of lines in an if/else statement to a reasonable amount (basically should fit on one screen in your IDE). To do so it is sometimes possible to extract some logic and stick it into a private function. No problem at all. All modern IDE do that for you in 2 clicks.
So basically the previous template becomes.
MyType func (ArgType arg1,...) {
MyType result ;
if ( checks_here ) {
// 1 to 20 lines max,
encapsulate lengthy logic in full fledged private methods.
} else {
// throw, log, nullify result etc
}
return result ;
}
Rule 4. Inner IFs should always have an ELSE, and that ELSE should be different from the outer ELSE.
Explanation: If I end up with
MyType func (ArgType arg1,...) {
MyType result ;
if ( check_1 ) {
if (check_2) {
Do the real work
} else {
treat error condition
}
} else {
same error condition as above
}
return result ;
}
Then it's probably because my check analysis is not complete. It happens quite often.
I try to reach
MyType func (ArgType arg1,...) {
MyType result ;
if ( check_1 && check_2) {
Do the real work
} else {
same error condition as above
}
return result ;
}
That's all.
I found that, by observing this kind of conventions, I can process large Java projects with ofter complex business logics (like in ESBs, Web Services etc), at very little performance cost if any.