Write 1 line If statement using ternary operator in JAVa - java

Not sure its possible or not. I want to write 1 line if condition statement using ternary operator. Here is my code :
if(preconditionflag.equals("skip")){
System.out.println("Skipping this testcase due to earlier testcase failed");
return flag = "skip";
} else {
flag = "pass";
}
precondflag and flag are String paramaters. Also "else" part is optional to write so please provide code either with else part (flag = "pass") or without it.
Thanks in advance.

I assume your actual code looks like this:
if (preconditionflag.equals("skip")){
System.out.println("Skipping this testcase due to earlier testcase failed");
flag = "skip";
} else {
flag = "pass";
}
If not, the answer to your question is already no, because you can't return from a method in one part and not return from a method in the other part of the ternary operation.
The other obstacle speaking against a ternary operation here is the output on STDOUT. Ternary operators don't allow that, but if you really need to you can solve it by creating a helper method:
private void myMethod() {
...
flag = preconditionflag.equals("skip") ?
showMessageAndReturn("Skipping this testcase due to earlier testcase failed", "skip") :
"pass";
...
}
private String showMessageAndReturn(String message, String retVal) {
System.out.println(message);
return retVal;
}
This is an answer following your question exactly but I have difficulties to see an actual use for it in real life.

Related

Intellij inspection rule to simplify conditional algorithms

We have some short methods that convert some values from one domain to another, it usually have a huge switch block or several ifs, for instance:
private DomainB translateSomething(final DomainA data) {
DomainB result = null;
if (data != null) {
if (CONSTANT_A_VALUE_X.equals(data)) {
result = CONSTANT_B_VALUE_X;
} else if (CONSTANT_A_VALUE_Y.equals(data)) {
result = CONSTANT_B_VALUE_Y;
} else if (CONSTANT_A_VALUE_Z.equals(data)) {
result = CONSTANT_B_VALUE_Z;
} else {
result = CONSTANT_B_VALUE_W;
}
}
return result;
}
It may be a switch instead of if, or it can have more than one condition per result, or even receive more than one domain on the method parameters in order to help to determine one single result, that is why it could not be a map.
When I see this I apply a short-circuit on the first condition, and remove all else blocks and instead of assigning the value to a variable which will be returned in the end, I put the return inside the condition itself, resulting the following code:
private DomainB translateSomething(final DomainA data) {
if (data == null) {
return null;
}
if (CONSTANT_A_VALUE_X.equals(data)) {
return CONSTANT_B_VALUE_X;
}
if (CONSTANT_A_VALUE_Y.equals(data)) {
return CONSTANT_B_VALUE_Y;
}
if (CONSTANT_A_VALUE_Z.equals(data)) {
return CONSTANT_B_VALUE_Z;
}
return CONSTANT_B_VALUE_W;
}
I'm tired to do it several times, I know IntelliJ helps a lot with inspections rules, is there some rule on IntelliJ that suggest this?
You may use "Move return closer to computation of the value.." quick-fix of 'return' separated from the result computation inspection (Java | Code style issues | 'return' separated from the result computation), then apply "remove redundant 'else'" quick-fixes of Redundant 'else' inspection (Java | Control flow issues | Redundant 'else').

Should I avoid using "!" in if statement in Java?

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, If its true write a return statement before end tag? is this better way of writing return statement in java

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;

Why isn't my java code proceeding past my if statements?

Okay, I have never had this problem before so I am not sure how to word it or to repair it, I am building a java application that creates dealers, in that application I have the parameters passed in to the DealerFactory.createDealer method and proceed to first check if that dealer exists with a conditional statement that looks like this:
if (DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)) {
throw new Exception("Sorry That Dealer Already Exists");
} else if (DealerFactory.fetchDealer(loginId).getId().equals(DNo)){
throw new Exception("Sorry That Dealer Already Exists");
} else {
<< proceed with the rest of the method here >>
I have seen this done before so as to check the availability of the username and the id of the person being created. However after running it I found that if I create the dealer and the condition evaluates to true the if statement works just fine letting me know that I have created a user that already exists and I need to create him/her with new a different Id and username. However if the condition evaluates to false I never seem to make it into the else portion of the statement, I am getting no errors, no compilation issues, and no exceptions I have written the statement differently to try that, which wasn't really any different it just looked syntactically different:
if (DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)
|| DealerFactory.fetchDealer(loginId).getId().equals(DNo)) {
throw new Exception("Sorry That Dealer Already Exists");
}
I have included println statements to follow the program through its run and when the condition evaluates to false I never make it into the else statement. I cant seem to figure out why it is breaking on the condition statement when it is evaluated to false, any thoughts?
edit:::
Ok so that I can be of more assistance in helping you guys help me lol here is the method in its entirety, I apologize for not posting it in the first place
public static int create(String DNo, String name, String admin,
String loginId, String password, String callSrc, String voiSys,
String whoCall, String callBrt, String active, String adfEmail)
throws SQLException, Exception {
int validateResult = 0;
if (DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)
|| DealerFactory.fetchDealer(loginId).getId().equals(DNo)) {
throw new Exception("Sorry That Dealer Already Exists");
}
try {
DealerFactory.pool = DBConnector.getInstance();
DealerFactory.connect = DBConnector.getConnection();
DealerFactory.preparedStatement = connect
.prepareStatement("Insert Into Dealers (DNo, Dealer, Admin, Login, Password, CallSrc, VoiSys, WhoC, CBrt, Active, ADFemail) "
+ "values(?,?,?,?,?,?,?,?,?,?,?)");
DealerFactory.preparedStatement.setString(1, DNo);
DealerFactory.preparedStatement.setString(2, name);
DealerFactory.preparedStatement.setString(3, admin);
DealerFactory.preparedStatement.setString(4, loginId);
DealerFactory.preparedStatement.setString(5, password);
DealerFactory.preparedStatement.setString(6, callSrc);
DealerFactory.preparedStatement.setString(7, voiSys);
DealerFactory.preparedStatement.setString(8, whoCall);
DealerFactory.preparedStatement.setString(9, callBrt);
DealerFactory.preparedStatement.setString(10, active);
DealerFactory.preparedStatement.setString(11, adfEmail);
validateResult = DealerFactory.preparedStatement
.executeUpdate();
} catch (SQLException ex) {
System.err.println("Error: " + ex + "\n");
ex.printStackTrace();
} finally {
DBUtils.closePrepStatement(DealerFactory.preparedStatement);
DealerFactory.pool.freeConnection(DealerFactory.connect);
}
return validateResult;
}
First things first, you shouldn't chain methods like that due to dangers of NullPointerException
So this part:
if(DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId))
Could look something like this:
if(DealerFactory.fetchDealer(loginId) != null &&
DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId))
Or you could have a separate null check before all your if statements.
However, what you are doing is an overkill. This whole part:
DealerFactory.fetchDealer(loginId).getLoginId()
Returns null if you cannot find a dealer or loginId that you already have.
Assuming your fetchDealer() method returns null if dealer cannot be found.
Instead of:
if(DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)))
You can just do:
if(DealerFactory.fetchDealer(loginId) != null)
Another improvement you could do is to add a method to DealerFactory called dealerExists(String id) declared something like this:
boolean dealerExists(String id) {
return (YOUR_DATA_STRUCTURE_OF_DEALERS.get(id) != null);
}
Or even:
boolean dealerExists(String id) {
return (fetchDealer(loginId) != null);
}
This would allow for better logical flow of your code. Your if statement would be very clear then:
if(DealerFactory.dealerExists(loginId) {
throw new Exception("Sorry That Dealer Already Exists");
}
Also, the value DNo is the dealer number I presume and you are checking if a dealer exists with the provided loginId or the provided DNo. However, in you checks you are comparing the DNo to the loginId to check if a dealer exists. What exactly is the point of DNo and shouldn't the loginId be enough to determine that the dealer exists?
If you really need to check the DNo as well, just add it as a check within the methods I suggested above.
More information regrading the variables that you are passing into the conditional would be of great help, (i.e. loginId and DNo). The first thing I would do is simplify your conditions in the if & else if statements.
It seems like you could change the if conditional to be if(DealerFactory.fetchDealer(loginId)) and have it work just the same since if the factory returns a dealer with the ID that you are looking for, that dealer already exists. From my understanding of what you're trying to achieve, it's unnecessary to dig any deeper. Also try running through this section of code with the debugger and monitor variables step-by-step to see what things look like at each line of code.
Edit:
You could also move the expressions outside of the conditional and set them to variables. For example:
int dealerId = DealerFactory.fetchDealer(loginId);
if(dealerId != null && dealerId != loginId) {
//<< proceed with the rest of the method here >>
} else {
//<<throw exception>>
}
Checking to see if dealerId is null in the conditional would avoid NullPointerExceptions, and declaring things outside of the conditional will make it easier to debug by hand.

Checking for multiple error conditions

I want to verify multiple conditions for validations. Currently, I have it set up such that in case of an error, each condition returns the error message, and an empty string in the absence of any errors. As a result, my code looks something like this:
String error = condition1(argA, argB);
if (!"".equals(error)) {
return error;
}
error = condition2(argC, argD);
.
.
.
and so on.
I wanted to know if there's a more elegant way of doing this in Java (or cofeescript)?
How about rather than having a lot of if statements you just create one method to check since if seems the check is the same for all conditions like.
public String check(String err)
{
if (!"".equals(err))
{
return err;
}
return err;
}
Now whenever you checking you just call the method
check(condition1(argA,argB));
and
check(condition2(argC,argB));
The string returned ofcause you know what to do with it.
Hope that helps

Categories