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
Related
I am quite new to the concept of Optional. In the code posted below, i am checking the following:
if (operation_1) {
if (operation_2) {
if (operation_3) {
} else {
throw_3
}
} else {
throw_2
}
} else {
throw_1
}
but for this code, android studio, generates an error for the second orElseThrow() operation "marked below".
please let me why I receive this error?how to fix it? whether or not the code i wrote below satisfies the conditions shown above.
code:
OptionalsUtils.toOptional(Room.databaseBuilder(getApplicationContext(), MovieDatabase.class, ActMain.DATA_BASE_NAME))//operation_1
.map(x->{
MovieDatabase movieRoomDb = x.fallbackToDestructiveMigration().build();
this.setInitializedBuiltMovieRoomDatabase(movieRoomDb);
return movieRoomDb;
})//operation_2
.map(y->{
SupportSQLiteOpenHelper openHelperInstance = y.getOpenHelper();
this.setSQLOpenHelperInstance(openHelperInstance);
return openHelperInstance;
})//operation_3
.orElseThrow(()-> new NullPointerException(THROW_SQL_OPEN_HELPER_NULL))//throw_3
.orElseThrow(()-> new NullPointerException(THROW_ROOM_DATABASE_PERSISTENT_BUILD_NULL))//throw_2<-cases error
.orElseThrow(()-> new NullPointerException(THROW_ROOM_DATABASE_PERSISTENT_BUILDER_NULL));//throw_1
I wouldn't recommend using an Optional here as it's not meant to
replace simple "if" cases.
instead, invert the if conditions to remove the nesting:
if (!operation_1)
throw_1;
if(!operation_2)
throw_2;
if(! operation_3)
trow_3;
...
...
As for your code, you cannot just chain orElseThrow methods as shown because the first call to orElseThrow will return the value encapsulated within the Optional if present otherwise throws the supplied exception thus the result of this method call is no longer an Optional.
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.
I have 3 fields (name, password, email). I want to check if they are valid or not. I wrote the following
public boolean isValidInput() {
if(name.isValid()){
return false;
}
if(password.isInValid()){
return false;
}
if(email.isInValid()){
return false;
}
return true;
}
so this will give me a single invalid. But what to do if I want to show the invalids all at the same time?
There are multiple ways you can handle this. But each of them need a change in the caller to handle these cases.
Create a custom exception which accepts a list of messages. Every time a validation failed add the error to the list, at the end of isValidInput() if the list is not empty then throw an exception with the list of errors.
Return the list of errors from above, instead of throwing exception.
Return a list of boolean variable and each index in the list will represent the status of a validation (name, email, etc)
Have an Enum of all fields that are present. Return a list of enum that failed. Empty list indicates that no error has occurred.
There are still a lot of other ways to handle this. It all depends on what suits you the best.
I would say, try some of them and see how it goes.
You could simply return an integer from the function like this
public int isValidInput() {
if(name.isValid()){
return 1;
}
if(password.isInValid()){
return 2;
}
if(email.isInValid()){
return 3;
}
return 0;
}
and then check the integer to find out which one failed!
It would be better of course to define static final ints with the names of the errors to make the code more readable and robust.
I have a method that returns all the names of people in a LinkedList for a plane.
However even though there is a return statement in the method, I'm still getting told there is a missing return statement.
How can I work around this without putting another return statement in? Why isn't it considered valid? Does putting another return statement in change what is returned?
Any feedback is greatly appreciated.
public String check() {
for (Person person: passengers)
{
return person.getName();
}
}
Because if passengers is empty, the loop will never be entered.
If the loop is never entered, assuming the only return statement is in it, we have a serious problem, don't you think ? It's like if there were no return at all.
You need to add another return statement outside of the loop.
Also note that the return will automatically exit the method, so I don't think this is exactly what you wanted as per this sentence in your question :
I have a method that returns all the names of people in a LinkedList
for a plane.
Edit
As per your edit, here how you can return a list containing all names :
return passengers.
.stream()
.map(Person::getName)
.collect(Collectors.toList());
Note that you will need to change the signature of your method to
public List<String> check()
In answer to your question in the comments. You can only return a single object from a function. You could take another container and populate it with the names and return that. For example,
public LinkedList<String> check() {
LinkedList<String> names = new LinkedList<String>();
for (Person person: passengers) {
names.add( person.getName() );
}
return names;
}
What exactly are you trying to accomplish, here?
Currently, check will only ever return the name of the first passenger. Think about how your program flows and what you want it to do.
To answer your question, you need to have an 'escape' for every possible path in your code. Even if a certain block should always catch and return (not by definition, but just by how you think the code should flow), you need to handle the case such that that block doesn't catch and return. This can be done by either fixing the first block so that it really is a catch-all, or by simply returning or throwing an error if the first block doesn't catch.
i.e.
public boolean check() {
...
if (shouldAlwaysBeTrue) return false;
}
doesn't work because shouldAlwaysBeTrue is not true by definition.
public boolean check() {
...
if (shouldAlwaysBeTrue) return false;
return true;
}
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