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
Related
I have this logic in my code
if(r40.isChecked()){
//do this
}
It works great, but I needed the negative, "if rb.isNotChecked" or ".isChecked() = false"
But I cant see to find it, also I can't use the RadioGroup because all my RadioButtons are not inside one, I'm controlling them manually
But I cant see to find it
if(!r40.isChecked()){
//do this
}
I mean you COULD do if(r40.isChecked() == false){
//do something
}
BUT if(!r40.isChecked){
//do something
} Is much better/cleaner
Try with negative check
if(!r40.isChecked()){
//do this
}
this check if radio isn`t checked.
Try this:
if (! r40.isChecked()) {
//Do something
}
In more detail the exclamation mark added in this code reverses the following code in the same block, causing the code to mean:
if (r40.isNotChecked()) {
//Do something
}
I hope this helped!
Our team's Java Coding Guideline says:
Avoid using "!" in if statement as much as possible.
I have asked other colleagues, but no one gave me clear ideas why, because the guideline was created a long time ago and the author might have left our company.
Do you have any idea?
With the information provided, this calls for some speculation. One possible reason is that the intent was not for an if-statement by itself but for an if-else statement. In that case, I can see where you might say that you should reverse the cases so that you don't have the extra operation of the negation. Instead of
if (! boolVar) {
// Something
} else {
// Something else
}
you might prefer
if (boolVar) {
// Something else
} else {
// Something
}
Whether this is worth it or not is probably more a matter of taste and standardization than anything else.
The rule is likely an adaptation from Robert Martin's Clean Code, page 302:
Negatives are just a bit harder to understand than positives. So, when possible, conditionals should be expressed as positives. For example:
if(buffer.shouldCompact())
is preferable to
if(!buffer.shouldNotCompact())
As an example, suppose you're creating a validator that requires two things to be false for the entity to be valid:
The entity must not have been created within the last 12 hours, and
The entity's bank account total sum must not exceed $50,000.
Naturally the idea would be to write two methods for this:
boolean isCreatedWithinLastTwelveHours(BankAccount account)
boolean hasMoreThanTotalSumCap(BankAccount account)
...at which point, you then invoke these as:
boolean newAccount = isCreatedWithinTheLastTwelveHours(account);
boolean highEndAccount = hasMoreThanTotalSumCap(account);
if(!newAccount && !highEndAccount) { // ... other logic
// The more astute would use DeMorgan's law in an effort to make this more readable
if(!(newAccount || highEndAccount)) { // other logic
Well...wouldn't it be nicer if you just said what they weren't instead?
boolean isNotCreatedWithinLastTwelveHours(BankAccount account)
boolean hasLessThanTotalSumCap(BankAccount account)
That'd make the expression a bit more concise:
if(notNewAccount && notHighEndAccount) { // .. carry on!
Of course "!" can be used when you like. There is no "unless" in java and you have no other choices in some conditions.
Looks like yet-another-useless-rule. Generally speaking, there are no absolute terms in this scenario, true that if you are in a if-else clause then possibly it is better to write
if(myCondition) {
doThis()
} else {
doSomethingElse()
}
Instead of
if(!myCondition) {
doSomethingElse()
} else {
doThis()
}
However, that said, in some scenarios is actually quite ok to use the negation operator, particularly if no else clause is provided, example
if (!tokenDoesCompute()) {
throw InvalidTockenException("Whatever")
}
And actually in that scenario, using "!" makes quite a bit of sense for me.
Finally, if no one can really explain WHY the rule is there, maybe it is time to remove it, the only good reason I could find for it would be to provide consistency regarding the code style.
Okay, I answer my own question.
As other say, maybe this is written for the readability.
In The Art of Readable Code (p. 72) says:
Prefer dealing with the positive case first instead of the negative-e.g., if(debug) instead of if(!debug)
I found below post as well:
Readable Code - Remove Checking null
bool func(String name)
{
if ( (name != null) && (name.equals("true") ) {
//...
} else {
//...
}
}
bool func(String name)
{
if ( "true".equals(name) ) {
//...
} else {
//...
}
}
Ofcourse you can use the negation operator ! whenever you like.
However, if you have a situation where you have to write some actions in both if and else block then the following is more readable :
if(status){
//do something
}
else{
//do something else
}
than
if(!status){
//do something
}
else{
//do something else
}
But if you have situation where you only need to perform certain actions based on just one condition, i.e. if you have only an if block & no else block, then it is reasonably fine to use ! in if
I haven't seen anyone else suggest this, which is probably because they hate it as much as I do, but I'm showing it for completeness.
// Using not operator (preferred)
if (! someTest) { ... }
// Using compact not operator (kind of hides it)
if (!someTest) { ... }
// Comparing to false (ok, explicitly states what you want)
if (someTest == false) { ... }
// Comparing to true (a bit obscure)
if (someTest != true) { ... }
They all do the same, but please keep using !, just make sure you add a space after it, so it's easier to see.
I have a if condition like the below
if (!null= xya)
return xya
{
a=b;
return abc
}
or which is it better to avoid return statement before entering in to loop
I'm very confused about the question, but this is how I imagine that code should look:
if (xya != null){
return xya;
}
else{
a=b;
return abc;
}
I have absolutely no idea what this code is meant to do, or why you need to declare a = b then return abc but if you're wondering why your code doesn't work that's probably it. As the other answer suggests, it's possible to completely remove the else case, but I feel like you need to keep your code as rigidly structured as possible for the time being.
Interpreting your question as, "Is there a better way to write a return statement, i.e. without using an if block?" If this isn't what you requested, please rewrite your question, as it is very difficult to understand what you're asking.
From your code, I'm thinking that you're trying to do a null-check, and return xyz if it's not null. Otherwise, do some other code, and return abc. Let's fix your code first.
if (xyz != null) {
return xyz; // Remember that after every statement, you need to have a semicolon.
} else {
a = b;
return abc;
}
You don't need to write an else statement within an if block. Knowing this, since your code would end if it xyz was not null, we don't need to write our code in the else statement, because the code after the if block is independent of the if block. Let's revise your code, then.
Try this:
if (xyz != null)
return xyz; // Since it's only one line, brackets are optional.
a = b;
return abc;
If you're coming from a different language (i.e. Lua), I'd highly recommend reading some syntax tutorials on Java. It'll save you a lot of frustration later. I recommend the following Java Tutorials, and just explore and read from the beginning. It's a great way to get the basics of syntax, especially with if statements.
Edit:
I've been told that bracketless conditionals may hinder code readability. Here are some alternatives to writing without them:
if (xyz != null) {
return xyz;
}
a = b;
return abc;
You could alternatively have the if statement in one line, as shown:
if (xyz != null) { return xyz; }
a = b;
return abc;
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
}
}
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.