Related
Can anyone assist me with an alternative to if then else statements for control flow? Or advise on a good article?
From what I've seen, some use mapping or enums. Trouble I'm having is that I have multiple conditions i.e. if (condition1 && condition2 && condition3)... and I need to do this for several permutations and all 3 variables need to be validated.
Please can someone point me in the right direction?
else if (String.Utils.isNotEmpty(payload.getKeyChange2TokenNumber()) && String.Utils.isEmpty(payload.getKeyChange1TokenNumber()) && String.Utils.isEmpty(payload.getKeyChange3TokenNumber()){
String.format(return value dependant on outcome of validation)
}
So no if then else statements, how can I implement a hashmap to determine what to return in place of the if then else statements return
Thank you.
So, a lot of people end up trying to avoid using if statements because they feel "there must be an easier and more cleaner way of doing this". However think fundamentally, code is just a bunch of if statements at the basic level.
So I wouldn't be too worried about using them, because by trying to use HashMaps or whatever, then you may be just using a nuclear bomb to kill a mosquito.
One thing to keep in mind is that you don't want nested if/else statements, it does become hard to check.
For your example, you mention that you have to do this check on the variables multiple times. So what's wrong with checking that they aren't empty at the start of the flow. If they are then exit or return with the corresponding result. You then don't need to do the checks again.
Additionally, it is useful to use short functions that describe what you're trying to do.
Instead of:
else if (String.Utils.isNotEmpty(payload.getKeyChange2TokenNumber())
&& String.Utils.isEmpty(payload.getKeyChange1TokenNumber())
&& String.Utils.isEmpty(payload.getKeyChange3TokenNumber()) {
String.format(return value dependant on outcome of validation)
}
Try:
if (notEmpty(payload.getKeyChange2TokenNumber())
&& notEmpty(payload.getKeyChange1TokenNumber())
&& notEmpty(payload.getKeyChange3TokenNumber())) {
String.format(return value dependant on outcome of validation)
}
private boolean notEmpty(String string) {
return StringUtils.isNotEmpty(string);
}
Additionally, if the above check is actually related to a domain related response then use that instead. For example, let's say getKeyChange1TokenNumber, getKeyChange2TokenNumber, getKeyChange3TokenNumber are all checked to determine whether the mandatory key change token numbers are provided and you cannot proceed if it isn't true. You're code would look like this:
public void main() {
if (mandatoryKeyChangeTokensNotProvided(payload)) {
return "Mandatory Key Change Tokens not provided";
}
...
}
private boolean mandatoryKeyChangeTokensNotProvided(Payload payload) {
return isEmpty(payload.getKeyChange2TokenNumber())
&& isEmpty(payload.getKeyChange1TokenNumber())
&& isEmpty(payload.getKeyChange3TokenNumber());
}
private boolean isEmpty(String string) {
return StringUtils.isEmpty(string);
}
Try to use the domain language in your code so it makes more sense to the dev. So a dev reading this would read the mandatoryKeyChangeTokensProvided method and know what it does. If they want to know how it does it, then just go into the method and see that its doing string empty checks against it. Hopefully this clears things up for you.
There are multiple ways you can do this, but it all depends on your domain. For example, you say this is validation? Whats wrong with having a Validator Class that does all these checks for you? But remember the KISS principle. Try not to overcomplicate things.
Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:
if(a == b);
// Do stuff
Which basically means that the stuff will be done whether a equals b or not, and the if statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?
Why does it happen?
Java Language Specification says that:
The Empty Statement
An empty statement does nothing.
EmptyStatement:
;
Execution of an empty statement always completes normally
It essentially means that you want to execute empty statement if a==b
if(a == b);
What should you do:
There are two main solutions to this problem:
You can avoid problems with empty statement by using code formatter
and surrounding stuff inside if with { and }. By doing this
Your empty statement will be much more readable.
if(a == b){
;
}
You can also check tools used for static code analysis such as:
Findbugs
Checkstyle
Pmd
They can instantly highlight problems such as this one.
I would recommend to combine both solutions.
Is there any situation in which this would be useful?
Useful? As in "makes your code cleaner, clearer, faster, more maintainable"? Not at all. This is most likely poor, confusing code.
But it's not necessarily benign. Such a statement can perform actions and/or alter state due to methods which cause side effects, and optionally evaluate those methods due to short-circuiting of operators.
if( a() && b() );
Here, a() or b() may do something, and b() will only execute if a() is true.
As to why, I think the answer is simply that it would be worse to deviate from defined, expected behavior (e.g. statements like while(reader.read());) than the alternative of developers writing bad code.
Writing bad code is always possible. And just to reiterate, this would be bad code in almost any case.
A possible use case:
if (a==b);
else {
// Do something
}
Not good, but possible.
Still, I do think that the Java specification should disallow an empty if.
If you're using Eclipse, you can make it warn you about those statements:
If you use an if statement, the first statement after the if will be executed if the condition is true. If you have a block after the if (with curly braces), it counts for that whole block. If there is no block it counts for only one statement. A single semicolon is an empty statement. You could also write the code from you example like this:
if(a==b) {
;
}
It is an old leftover from the days when there was more syntactic sugar to differentiate expressions from statements.
Basically, the comma was used as the list item separator, so the semicolon was used as the "list of statements" separator. The downside is in the handling of null items in lists, and null statements in blocks.
In a list of items, Java uses the explicit keyword null, but a "null statement" is just an empty line. Allowing the existence of an empty line is a holdover from tradition inherited from C.
Why do it? Especially with an if statement when you know that no statements are being executed: Because some if statements have side effects:
int c;
if ((c = in.read()) != -1);
Yes, it is not the best example, but basically it says read a byte from the stream and do nothing. Might be useful in some corner cases, but even if this example isn't the best, it illustrates the intent. We want to feel the side-effects of the expression without accidentally executing any statements.
I can't think of an occasion where it is useful. It can be useful for loops like
while(do something);
or
for(init; do something; something else);
If you use your code formatting in your IDE regularly these sort of bugs become obvious. Some IDEs highlight this as a probable bug as well.
I'd agree with you there's no useful purpose to this for a human. I suspect it's there because it simplifies the language definition; it means that the thing that comes after an if is e same as the thing that comes after a while, for instance.
Why? It's because its easier for compiler writers. You don't have to make a special case to check for semicolons after if(cond) and has an added usage of allowing
if (cond && maybeFunc())
;// Code here I want to ignore
Even though it's actually a terrible idea to allow this. It's just easier to allow and then to add a case to check this.
Java allows an empty block any place a statement block is allowed. I am sure making this a general rule for all blocks simplifies the compiler.
I agree that this is primarily the cause of bugs that are spectacularly hard to find. I always use braces around blocks, even when there is a single statement, but Java allows you to make a block with braces at any point, so using braces can not save you from this fate. For example, I once wasted 4 hours trying find something like this:
while (condition);
{
statement;
statement;
}
The semicolon at the end of the first line was a typo, accidentally making the statement block for the while loop empty. Because the syntax is valid the program compiled and ran fine, just not the way I wanted it to. It was really hard to find.
I can think of one situation where it is very nice that you are allowed to have empty blocks, and this is something like this:
if (condition1) {
do_action_1();
}
else if (condition2) {
//nothing really to do in this case
}
else if (condition3) {
do_action2();
}
else {
do_action3();
}
In the above example, you want to be able to separate out various conditions. Remember, those conditions might be overlapping, so it is not always possible to rearrange the order. If one of the conditions really does not need anything done, then it is nice that Java allows you to have an empty block. Otherwise, the language would need some form of a "noop" method to use when you really do not want anything done.
I personally would prefer the explicit "noop" statement -- but that is not how Java is defined.
Just a FYI about the usability and what difference it makes or can make if there is a statement like that
Consider a piece of code like the following.
int a = 10;
if ((a = 50) == 50);
System.out.println("Value of a = " + a);
Clearly in this case, the if statement does change the output. So a statement like that can make a difference.
This is a situation where this could be useful or better to say have an impact on program.
if(a==b)
println("a equals b");
You can use an IF statement without {} if there is only a single line to be executed, so by using if(a==b); you are saying if they equal, execute and empty statement... So it will do nothing, and then return to your normal loop, outside of the IF block.
A few definitions from the jls explain this (chapter 14):
Blocks are Statements
As stated here, a Block is a StatementWithoutTrailingSubstatement, which in turn is a StatementNoShortIf, which is a Statement. Thus where ever any of these is required, we can insert a Block.
The if-clause
Though this is as well the case for for and while-loops, I'll use if-statements. These rules are pretty much the same. The syntactical description of if-statements can be found here.
IfThenStatement:
if ( Expression ) Statement
IfThenElseStatement:
if ( Expression ) StatementNoShortIf else Statement
IfThenElseStatementNoShortIf:
if ( Expression ) StatementNoShortIf else StatementNoShortIf
So we can use our block here.
But why does it work with ; ?
; is defined as the EmptyStatement (link), which is as well a StatementNoShortIf. So in conditional pieces of code, like if-statement and loops, we can replace a Block with a EmptyStatement, if a StatementNoShortIf or Statement is required.
Thus if(Expression)EmptyStatement works.
Why doesn't this give an error?
Pretty simple: java gives an error if it finds invalid syntax. But if(Expression)EmptyStatement is perfectly valid syntax. Instead javac gives a warning if launched with the proper parameters. The full list of warnings that can be dis-/enabled lists the warning-name empty for this purpose. So compilation with -Xlint:all or -Xlint:empty will generate a warning about this.
Your IDE should have an option to enable this kind of warning as well.
For eclipse, see #nullptr's answer. In IntelliJ, you can press Ctrl + Shift + A, enter empty body into the search field and enable the warning (marked in the image)
What is this even used for?
To be honest, there's not much use in it from a minimalistic point of view. There's usually a way to get things done without a "do nothing" command. It's rather a question of personal preferences, whether you rather use
if( a() && b() );
or
if( a() ) b();
and same would apply to other cases, in which the EmptyStatement is used. An important point to consider on this topic is readability of code. There are occasions, where code becomes more readable by using the no-op. On the other hand there are cases, where code becomes quite a lot harder to comprehend with using the EmptyStatement - the above example would count to the later IMO.
I can think of a scenario where an empty statement is required (not for if condition but for while loop).
When a program just want an explicit confirmation from the user to proceed. This may be required when the work after the user confirmation depends on some other things and user want to take control of when to proceed.
System.out.println("Enter Y to proceed. Waiting...");
System.out.println("");
while(!(new Scanner(System.in).next().equalsIgnoreCase("Y")));
System.out.println("Proceeding...");
// do the work here
look this:
int a,b,c = 0;
if(a == b){
c =1;
}
System.out.print(c);//1
so, you can write like this:
if (a == b)c=1;
but,if this code is this:
int a,b,c=0;
if (a != b){
}
if (a == b ){
c =1;
}
you can write like this:
if(a != b);
if(a == b )c=1;
so,you will know if(a != b); do noting
The semi-colon in the if indicates the termination of the if condition as in java ; is treated as the end of a statement, so the statement after if gets executed.
Semicolon at the end of,
if(a==b); simply finish the statement in single line which means ignore the result of condition and continue the execution from the next line
This code is useful, on the other hand sometime introduce bug in program, for example,
case 1.
a = 5;
b = 3;
if(a == b);
prinf("a and b are equal");
case 2.
a = 5;
b = 5;
if(a == b);
prinf("a and b are equal");
would print the same output on the screen...
While working on a programming assignment for class where I am working with a N by N grid of doodads and comparing characteristics of a random doodad to those above, below, left, and right, I found a nice use of this to prevent nested statements and potential boundary exceptions. My goal was to minimize code and keep from nesting if-statements.
if (row == 0);
else (method (grid[row][col], grid[row-1][col]));
if (row == N-1);
else (method (grid[row][col], grid[row+1][col]));
if (col == 0);
else (method (grid[row][col], grid[row][col-1]));
if (col == N-1);<br>
else (method (grid[row][col], grid[row][col+1]));
where method(Doodad a, Doodad b) does some operation between a and b.
Alternatively, you could use exception handling to avoid this syntax, but it works and works well for my application.
I have found myself using the following practice, but something inside me kind of cringes every time i use it. Basically, it's a precondition test on the parameters to determine if the actual work should be done.
public static void doSomething(List<String> things)
{
if(things == null || things.size() <= 0)
return;
//...snip... do actual work
}
It is good practice to return at the earliest opportunity.
That way the least amount of code gets executed and evaluated.
Code that does not run cannot be in error.
Furthermore it makes the function easier to read, because you do not have to deal with all the cases that do not apply anymore.
Compare the following code
private Date someMethod(Boolean test) {
Date result;
if (null == test) {
result = null
} else {
result = test ? something : other;
}
return result;
}
vs
private Date someMethod(Boolean test) {
if (null == test) {
return null
}
return test ? something : other;
}
The second one is shorter, does not need an else and does not need the temp variable.
Note that in Java the return statement exits the function right away; in other languages (e.g. Pascal) the almost equivalent code result:= something; does not return.
Because of this fact it is customary to return at many points in Java methods.
Calling this bad practice is ignoring the fact that that particular train has long since left the station in Java.
If you are going to exit a function at many points in a function anyway, it's best to exit at the earliest opportunity
It's a matter of style and personal preference. There's nothing wrong with it.
To the best of my understanding - no.
For the sake of easier debugging there should be only one return/exit point in a subroutine, method or function.
With such approach your program may become longer and less readable, but while debugging you can put a break point at the exit and always see the state of what you return. For example you can log the state of all local variables - it may be really helpful for troubleshooting.
It looks like there a two "schools" - one says "return as early as possible", whereas another one says "there should be only one return/exit point in a program".
I am a proponent of the first one, though in practice sometimes follow the second one, just to save time.
Also, do not forget about exceptions. Very often the fact that you have to return from a method early means that you are in an exceptional situation. In your example I think throwing an exception is more appropriate.
PMD seems to think so, and that you should always let your methods run to the end, however, for certain quick sanity checks, I still use premature return statements.
It does impair the readability of the method a little, but in some cases that can be better than adding yet another if statement or other means by which to run the method to the end for all cases.
There's nothing inherently wrong with it, but if it makes you cringe, you could throw an IllegalArgumentException instead. In some cases, that's more accurate. It could, however, result in a bunch of code that look this whenever you call doSomething:
try {
doSomething(myList);
} catch (IllegalArgumentException e) {}
There is no correct answer to this question, it is a matter of taste.
In the specific example above there may be better ways of enforcing a pre-condition, but I view the general pattern of multiple early returns as akin to guards in functional programming.
I personally have no issue with this style - I think it can result in cleaner code. Trying contort everything to have a single exit point can increase verbosity and reduce readability.
It's good practice. So continue with your good work.
There is nothing wrong with it. Personally, I would use else statement to execute the rest of the function, and let it return naturally.
If you want to avoid the "return" in your method : maybe you could use a subClass of Exception of your own and handle it in your method's call ?
For example :
public static void doSomething(List<String> things) throws MyExceptionIfThingsIsEmpty {
if(things == null || things.size() <= 0)
throw new MyExceptionIfThingsIsEmpty(1, "Error, the list is empty !");
//...snip... do actual work
}
Edit :
If you don't want to use the "return" statement, you could do the opposite in the if() :
if(things != null && things.size() > 0)
// do your things
If function is long (say, 20 lines or more), then, it is good to return for few error conditions in the beginning so that reader of code can focus on logic when reading rest of the function. If function is small (say 5 lines or less), then return statements in the beginning can be distracting for reader.
So, decision should be based on primarily on whether the function becomes more readable or less readable.
Java good practices say that, as often as possible, return statements should be unique and written at the end of the method. To control what you return, use a variable. However, for returning from a void method, like the example you use, what I'd do would be perform the check in a middle method used only for such purpose. Anyway, don't take this too serious - keywords like continue should never be used according to Java good practices, but they're there, inside your scope.
Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:
if(a == b);
// Do stuff
Which basically means that the stuff will be done whether a equals b or not, and the if statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?
Why does it happen?
Java Language Specification says that:
The Empty Statement
An empty statement does nothing.
EmptyStatement:
;
Execution of an empty statement always completes normally
It essentially means that you want to execute empty statement if a==b
if(a == b);
What should you do:
There are two main solutions to this problem:
You can avoid problems with empty statement by using code formatter
and surrounding stuff inside if with { and }. By doing this
Your empty statement will be much more readable.
if(a == b){
;
}
You can also check tools used for static code analysis such as:
Findbugs
Checkstyle
Pmd
They can instantly highlight problems such as this one.
I would recommend to combine both solutions.
Is there any situation in which this would be useful?
Useful? As in "makes your code cleaner, clearer, faster, more maintainable"? Not at all. This is most likely poor, confusing code.
But it's not necessarily benign. Such a statement can perform actions and/or alter state due to methods which cause side effects, and optionally evaluate those methods due to short-circuiting of operators.
if( a() && b() );
Here, a() or b() may do something, and b() will only execute if a() is true.
As to why, I think the answer is simply that it would be worse to deviate from defined, expected behavior (e.g. statements like while(reader.read());) than the alternative of developers writing bad code.
Writing bad code is always possible. And just to reiterate, this would be bad code in almost any case.
A possible use case:
if (a==b);
else {
// Do something
}
Not good, but possible.
Still, I do think that the Java specification should disallow an empty if.
If you're using Eclipse, you can make it warn you about those statements:
If you use an if statement, the first statement after the if will be executed if the condition is true. If you have a block after the if (with curly braces), it counts for that whole block. If there is no block it counts for only one statement. A single semicolon is an empty statement. You could also write the code from you example like this:
if(a==b) {
;
}
It is an old leftover from the days when there was more syntactic sugar to differentiate expressions from statements.
Basically, the comma was used as the list item separator, so the semicolon was used as the "list of statements" separator. The downside is in the handling of null items in lists, and null statements in blocks.
In a list of items, Java uses the explicit keyword null, but a "null statement" is just an empty line. Allowing the existence of an empty line is a holdover from tradition inherited from C.
Why do it? Especially with an if statement when you know that no statements are being executed: Because some if statements have side effects:
int c;
if ((c = in.read()) != -1);
Yes, it is not the best example, but basically it says read a byte from the stream and do nothing. Might be useful in some corner cases, but even if this example isn't the best, it illustrates the intent. We want to feel the side-effects of the expression without accidentally executing any statements.
I can't think of an occasion where it is useful. It can be useful for loops like
while(do something);
or
for(init; do something; something else);
If you use your code formatting in your IDE regularly these sort of bugs become obvious. Some IDEs highlight this as a probable bug as well.
I'd agree with you there's no useful purpose to this for a human. I suspect it's there because it simplifies the language definition; it means that the thing that comes after an if is e same as the thing that comes after a while, for instance.
Why? It's because its easier for compiler writers. You don't have to make a special case to check for semicolons after if(cond) and has an added usage of allowing
if (cond && maybeFunc())
;// Code here I want to ignore
Even though it's actually a terrible idea to allow this. It's just easier to allow and then to add a case to check this.
Java allows an empty block any place a statement block is allowed. I am sure making this a general rule for all blocks simplifies the compiler.
I agree that this is primarily the cause of bugs that are spectacularly hard to find. I always use braces around blocks, even when there is a single statement, but Java allows you to make a block with braces at any point, so using braces can not save you from this fate. For example, I once wasted 4 hours trying find something like this:
while (condition);
{
statement;
statement;
}
The semicolon at the end of the first line was a typo, accidentally making the statement block for the while loop empty. Because the syntax is valid the program compiled and ran fine, just not the way I wanted it to. It was really hard to find.
I can think of one situation where it is very nice that you are allowed to have empty blocks, and this is something like this:
if (condition1) {
do_action_1();
}
else if (condition2) {
//nothing really to do in this case
}
else if (condition3) {
do_action2();
}
else {
do_action3();
}
In the above example, you want to be able to separate out various conditions. Remember, those conditions might be overlapping, so it is not always possible to rearrange the order. If one of the conditions really does not need anything done, then it is nice that Java allows you to have an empty block. Otherwise, the language would need some form of a "noop" method to use when you really do not want anything done.
I personally would prefer the explicit "noop" statement -- but that is not how Java is defined.
Just a FYI about the usability and what difference it makes or can make if there is a statement like that
Consider a piece of code like the following.
int a = 10;
if ((a = 50) == 50);
System.out.println("Value of a = " + a);
Clearly in this case, the if statement does change the output. So a statement like that can make a difference.
This is a situation where this could be useful or better to say have an impact on program.
if(a==b)
println("a equals b");
You can use an IF statement without {} if there is only a single line to be executed, so by using if(a==b); you are saying if they equal, execute and empty statement... So it will do nothing, and then return to your normal loop, outside of the IF block.
A few definitions from the jls explain this (chapter 14):
Blocks are Statements
As stated here, a Block is a StatementWithoutTrailingSubstatement, which in turn is a StatementNoShortIf, which is a Statement. Thus where ever any of these is required, we can insert a Block.
The if-clause
Though this is as well the case for for and while-loops, I'll use if-statements. These rules are pretty much the same. The syntactical description of if-statements can be found here.
IfThenStatement:
if ( Expression ) Statement
IfThenElseStatement:
if ( Expression ) StatementNoShortIf else Statement
IfThenElseStatementNoShortIf:
if ( Expression ) StatementNoShortIf else StatementNoShortIf
So we can use our block here.
But why does it work with ; ?
; is defined as the EmptyStatement (link), which is as well a StatementNoShortIf. So in conditional pieces of code, like if-statement and loops, we can replace a Block with a EmptyStatement, if a StatementNoShortIf or Statement is required.
Thus if(Expression)EmptyStatement works.
Why doesn't this give an error?
Pretty simple: java gives an error if it finds invalid syntax. But if(Expression)EmptyStatement is perfectly valid syntax. Instead javac gives a warning if launched with the proper parameters. The full list of warnings that can be dis-/enabled lists the warning-name empty for this purpose. So compilation with -Xlint:all or -Xlint:empty will generate a warning about this.
Your IDE should have an option to enable this kind of warning as well.
For eclipse, see #nullptr's answer. In IntelliJ, you can press Ctrl + Shift + A, enter empty body into the search field and enable the warning (marked in the image)
What is this even used for?
To be honest, there's not much use in it from a minimalistic point of view. There's usually a way to get things done without a "do nothing" command. It's rather a question of personal preferences, whether you rather use
if( a() && b() );
or
if( a() ) b();
and same would apply to other cases, in which the EmptyStatement is used. An important point to consider on this topic is readability of code. There are occasions, where code becomes more readable by using the no-op. On the other hand there are cases, where code becomes quite a lot harder to comprehend with using the EmptyStatement - the above example would count to the later IMO.
I can think of a scenario where an empty statement is required (not for if condition but for while loop).
When a program just want an explicit confirmation from the user to proceed. This may be required when the work after the user confirmation depends on some other things and user want to take control of when to proceed.
System.out.println("Enter Y to proceed. Waiting...");
System.out.println("");
while(!(new Scanner(System.in).next().equalsIgnoreCase("Y")));
System.out.println("Proceeding...");
// do the work here
look this:
int a,b,c = 0;
if(a == b){
c =1;
}
System.out.print(c);//1
so, you can write like this:
if (a == b)c=1;
but,if this code is this:
int a,b,c=0;
if (a != b){
}
if (a == b ){
c =1;
}
you can write like this:
if(a != b);
if(a == b )c=1;
so,you will know if(a != b); do noting
The semi-colon in the if indicates the termination of the if condition as in java ; is treated as the end of a statement, so the statement after if gets executed.
Semicolon at the end of,
if(a==b); simply finish the statement in single line which means ignore the result of condition and continue the execution from the next line
This code is useful, on the other hand sometime introduce bug in program, for example,
case 1.
a = 5;
b = 3;
if(a == b);
prinf("a and b are equal");
case 2.
a = 5;
b = 5;
if(a == b);
prinf("a and b are equal");
would print the same output on the screen...
While working on a programming assignment for class where I am working with a N by N grid of doodads and comparing characteristics of a random doodad to those above, below, left, and right, I found a nice use of this to prevent nested statements and potential boundary exceptions. My goal was to minimize code and keep from nesting if-statements.
if (row == 0);
else (method (grid[row][col], grid[row-1][col]));
if (row == N-1);
else (method (grid[row][col], grid[row+1][col]));
if (col == 0);
else (method (grid[row][col], grid[row][col-1]));
if (col == N-1);<br>
else (method (grid[row][col], grid[row][col+1]));
where method(Doodad a, Doodad b) does some operation between a and b.
Alternatively, you could use exception handling to avoid this syntax, but it works and works well for my application.
Which one is better Java coding style?
boolean status = true;
if (!status) {
//do sth
} else {
//do sth
}
or:
if (status == false) {
//do sth
} else {
//do sth
}
I would suggest that you do:
if (status) {
//positive work
} else {
// negative work
}
The == tests, while obviously redundant, also run the risk of a single = typo which would result in an assignment.
Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.
One more suggestion: Choose a different name for your boolean variable. As per this Java style guide:
is prefix should be used for boolean variables and methods.
isSet, isVisible, isFinished,
isFound, isOpen
This is the naming convention for
boolean methods and variables used
by Sun for the Java core packages.
Using the is prefix solves a common
problem of choosing bad boolean names
like status or flag. isStatus or
isFlag simply doesn't fit, and the
programmer is forced to chose more
meaningful names.
Setter methods for boolean variables
must have set prefix as in:
void setFound(boolean isFound);
There are a few alternatives to the
is prefix that fits better in some
situations. These are has, can and
should prefixes:
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;
If you look at the alternatives on this page, of course the first option looks better and the second one is just more verbose. But if you are looking through a large class that someone else wrote, that verbosity can make the difference between realizing right away what the conditional is testing or not.
One of the reasons I moved away from Perl is because it relies so heavily on punctuation, which is much slower to interpret while reading.
I know I'm outvoted here, but I will almost always side with more explicit code so others can read it more accurately. Then again, I would never use a boolean variable called "status" either. Maybe isSuccess or just success, but "status" being true or false does not mean anything to the casual reader intuitively. As you can tell, I'm very into code readability because I read so much code others have written.
The first one, or if (status) { /*second clause*/ } else { /* first clause */ }
EDIT
If the second form is really desired, then if (false == status) <etc>, while uglier, is probably safer (wrt typos).
It really also depends on how you name your variable.
When people are asking "which is better practice" - this implicitly implies that both are correct, so it's just a matter of which is easier to read and maintain.
If you name your variable "status" (which is the case in your example code), I would much prefer to see
if(status == false) // if status is false
On the other hand, if you had named your variable isXXX (e.g. isReadableCode), then the former is more readable. consider:
if(!isReadable) { // if not readable
System.out.println("I'm having a headache reading your code");
}
The former. The latter merely adds verbosity.
The first one. But just another point, the following would also make your code more readable:
if (!status) {
// do false logic
} else {
// do true logic
}
Note that there are extra spaces between if and the (, and also before the else statement.
EDIT
As noted by #Mudassir, if there is NO other shared code in the method using the logic, then the better style would be:
if (!status) {
// do false logic
}
// do true logic
My personal feeling when it comes to reading
if(!status) : if not status
if(status == false) : if status is false
if you are not used to !status reading. I see no harm doing as the second way.
if you use "active" instead of status I thing if(!active) is more readable
First style is better. Though you should use better variable name
This is more readable and good practice too.
if(!status){
//do sth
}else{
//do sth
}