More simple logic condition to check non-empty requirements - java

I have some simple logic to check if the field is valid:
private boolean isValidIfRequired(Object value) {
return
(required && !isEmpty(value)) || !required;
}
it tells that the field is valid if it's either required and not empty or not required.
I don't like this required || !required part. Something with just required would be better.
How do I simplify this method to make it more readable and simple?

How 'bout:
private boolean isValidIfRequired(Object value) {
return !required || !isEmpty(value);
}
or (thanks, #Peter Lawrey)
private boolean isValidIfRequired(Object value) {
return !(required && isEmpty(value));
}
In either case, if required is false, the || or && expression will short-circuit and isEmpty will never be called. If required is true, the second half of the || or && will be evaluated, calling isEmpty and returning the (inverted) result of that call.

The expected return of isValidIfRequired() is to return true.
So the exceptional cases must be put at the beginning as guardian clausules:
private boolean isValidIfRequired(Object value) {
if (required && empty(value)) //guardian clausule
return false;
return true;
}
for me the above code is more human-readable than using together expresions containing ANDs ORs and negations

Related

Return boolean on the basis of multiple condition

I have a use-case where I want to return boolean value from the function
private boolean checkStatus(String param) {
return param != null ? randomBool() : true;
}
private boolean randomBool() {
// return true or false on the basis of some condition
}
I am getting complaint issue over true statement. What could be the other way to achieve the same?
Sonar issue: Redundant Boolean literals should be removed from expressions to improve readability.
Just change your code to the next:
param == null || randomBool()

String to Boolean.parseBooelan

I'm trying to write a boolean function that returns true or false.
private boolean isExist(Optional<List<Attributes>> attributes) {
if (attributes.get().stream().filter(att -> att.getAttributeName().equals("exist") && att.getAttributeValue().equals("true")).count() > 0) {
return true;
}
return false;
}
How can I make use of Boolean.parseBoolean instead att.getAttributeValue().equals("true")? Is there any advantage of using it?
You can (and should) map the Optional directly in case it's empty. Then you can pass Boolean.parseBoolean as a parameter to map.
return attributes.map(Attributes::stream)
.filter (att -> "exist".equals (att.getAttributeName()))
.map (Attribute::GetValue)
.map (Boolean::parseBoolean)
.orElse (false);
I think you can use:
if (attributes.isEmpty()) {
return false;
}
return attributes.get().stream().anyMatch(att ->
"exist".equals(att.getAttributeName()) &&
Boolean.parseBoolean(att.getAttributeValue())
);
How can I make use of Boolean.parseBoolean instead
att.getAttributeValue().equals("true")?
You can do it as follows:
private boolean isExist(Optional<Attributes> attributes)
{
if (attributes.get().stream().filter(att -> att.getAttributeName().equals("exist") && Boolean.parseBoolean(att.getAttributeValue())==true)).count() > 0) {
return true;
}
return false;
}
You need to check your optional first:
private boolean isExist(Optional<List<Attributes>> attributes) {
return attributes.map(list -> list.stream().anyMatch(YourClass::isMatch))
.orElse(false);
}
private static boolean isMatch(Attributes att) {
return att.getAttributeName().equals("exist") && Boolean.parseBoolean(att.getAttributeValue());
}
Because you are only interested on a single match you should use the anyMatch.
How can I make use of Boolean.parseBoolean instead att.getAttributeValue().equals("true")?
Is there any advantage of using it?
Yes,
public static boolean parseBoolean(String s) Parses the string
argument as a boolean. The boolean returned represents the value true
if the string argument is not null and is equal, ignoring case, to the
string "true".
With this method strings like "TruE" will be consider true, so you do not have to worry about upper and lower case stuff, and more important if you receive a null Boolean.parseBoolean(..) return False. Nevertheless, I think in your case, unless you have a good reason to not do it, the better option would actually be to change
att.getAttributeValue()
to return true of false instead of a String encoding a boolean.

How can I cast an Object in an equals override method in Java?

I have the following code in a class used to simulate the IRS with employer filings in accordance with the filer. I am required to override the equals class but I keep getting the error saying that the methods I am trying to use cannot be found when called on the casted Object.
#Override
public boolean equals(Object obj) {
if ((this == null )|| (obj == null) || (this.getClass() != obj.getClass()))
return false;
if ((this.sameEmployer((Employer)obj))
&& (this.getEmployeeSSN() == (Employer)obj.getEmployeeSSN())
&& (this.getName() == (Employer)obj.getName())
&& (this.getEmployeeName() == (Employer)obj.getEmployeeName())
&& (this.getEmployeeWages() == (Employer)obj.getEmployeeWages()))
return true;
else
return false;
}
Casting happens after method calls. According to the precedence of operators, () for method calling is at the highest level, 1, while () for casting is at level 3. In other words you are attempting to cast obj.getEmployeeSSN() as an Employer, not obj.
Once you know obj is an Employer, you can place parentheses to force casting first, e.g.
&& (this.getEmployeeSSN() == ((Employer) obj).getEmployeeSSN())
However, it looks like a mess of parentheses. For clarity, just declare an Employer variable, cast it once, then call the methods, passing the Employer variable.
Employer emp = (Employer) obj;
if (this.sameEmployer(emp)
&& ...
For expressions like this:
(Employer)obj.getEmployeeSSN()
The . has higher precedence - "binds tighter" - than the cast. So it's closer to:
(Employer) (obj.getEmployeeSSN())
... whereas you want:
((Employer) obj).getEmployeeSSN()
in order to cast and then call the method. That's most easily done by casting in an earlier line:
public boolean equals(Object obj) {
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
Employee other = (Employee) obj;
// Now use "other" in the rest of the code:
return sameEmployer(other)
&& getEmployeeSSN() == other.getEmployeeSSN()
...;
}
Note that:
this can never be null, so you don't need to test it
You don't need nearly as many brackets as you had before
I'd strongly encourage you to use braces for all if blocks... you'd be surprised at how easy it is to end up with mistakes otherwise. (There are lots of SO questions which are basically due to that...)
Any time you have:
if (foo) {
return true;
} else {
return false;
}
you should simplify it to:
return foo;
Class Object doesn't have getEmployeeSSN(). What you should have instead is :
(this.getEmployeeSSN() == ((Employer)obj).getEmployeeSSN() //and so forth.
The cast should happen first, then you try to use the method on the casted object
You just have a problem with priority of your operations. The cast to (Employer) will happen after you call the specific methods. To enforce the priority you need to add brackets:
((Employer) obj).getName()
instead of
(Employer) obj.getName()

Android: Can't check whether a string variable is null or not. How to check if a string variable is null or not?

I can't check whether a string is empty or not coming from rest service as input stream which then I am changing into string for parsing.
public boolean isNullorEmpty(String string)
{
if(string !=null || !string.isEmpty() || string.length()>0)
return true;
else
return false;
}
Please help me out to check if string is empty or not.
The current problem in your code is that if the string you pass in argument is null, thenstring !=null is evaluated to false. Hence you'll try to evaluate !string.isEmpty() which will lead to a NullPointerException.
On the other hand if you pass a String that is not null (ex "" or "test"), string != null is evaluated to true and hence you return true.
So to fix that you should, as the name of your method suggests, check if the String is null OR empty.
But since you're on android, don't reinvent the wheel and use TextUtils.isEmpty(CharSequence str).
boolean isEmpty = TextUtils.isEmpty(myString);
Returns true if the string is null or 0-length.
If you want to look about how is it implemented:
427 public static boolean isEmpty(CharSequence str) {
428 if (str == null || str.length() == 0)
429 return true;
430 else
431 return false;
432 }
Well, this can be handled in plain java like:
And it can be written like:
public boolean isStringEmpty (){
if(str ==null || str.isEmpty () || str.trim().equals("")){
return true;
}
return false;
}

Difference between these two appraoch in calling equals method?

Approach one.
if (graphType.equals("All") || graphType.equals("ALL"))
Aprroach two.
if ("All".equals(graphType) || "ALL".equals(graphType))
What is the difference between these two approaches?
Why the below one is better?
The second one is better, as if graphType is null, the first code snippet will throw a NullPointerException.
Note that you can simplify your code using "ALL".equalsIgnoreCase(graphType) (if you accept values such as AlL or aLL...)
Edit regarding your comment:
If graphType is null, in the first case, you will get a NullPointerException. In the second case, the evaluation of the equals method will be false, as "someString".equals(null); always returns false:
Here is the code of the String.equals(String) method:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
(source)
The interesting line is if (anObject instanceof String) {. When you call the instanceof statement on a null object, this test always returns false. That's why "anyString".equals(null); will return false.
I feel the need to present a contrarian viewpoint to the accepted answer:
The first one is better, precisely because it will throw a NullPointerException in the case where graphType is null.
Generally, if an unexpected condition is found, you want to halt and throw an Exception as early as possible, otherwise you may continue to execute the program in an invalid state and the bug may become fiendishly difficult to track down.
This is sometimes referred to as the "fail-fast" principle.
romaintaz answer is absolutely correct. However, if you're like me, you might prefer to use the first approach to make your code easier to read. This is where assertions come into play:
assert graphType != null : "graphType is null";
if (graphType.equals("All") || graphType.equals("ALL"))
The question is whether your users will find a creative way to make graphType = null once you've finished testing.
The other thing I don't like about the second approach is that it fails silently in the case that graphType is unexpectedly null -- It prevents a runtime error, but may present a bug that's difficult to track down.

Categories

Resources