Simplify two boolean expressions - java

I got a trouble on simplifying two boolean expressions.
boolean sayHi = true;
boolean isValid = someVariable.equals(new exampleClass("hello")) || someVariable.equals(new exampleClass("Hi"));
if (sayHi & !isValid) {
return;
}
How can i simplify this one? I think isValid looks quite big, is there a way to do it? Please help me.

boolean sayHi = true;
boolean valid = Arrays.asList("hello", "hi").contains(someVariable.getName());
if (sayHi && !valid) {
return;
}
Newer java would use Set.of (better semantics, performance).
isValid is more a name for a boolean getter.
Assumed is that "hello" and "hi" can be retrieved with a getter.

boolean sayHi = true;
if (sayHi && !someVariable.equals(new exampleClass("hello"))
&& !someVariable.equals(new exampleClass("Hi")))
return;

Related

Using a variable that is changed within an if statement

I am writing a program in JAVA where I need to change a boolean, but I am not able to fix it.
The lay out is as follows
while(statement){
Boolean behind = true;
if (behind == true){
do something
behind = false;
}
if (behind == false){
do something else
behind = true;
}
}
So basically my program needs to iterate 'doing something' and 'doing something else'. But I reckon my boolean behind is not changed by the if-statement, since that 'version' of behind only lives within the statement. Any suggestions on how to cope with this?
Do not use var == true/false. This may reduce performance and makes the code unclear. Use var instead of var == true and !var instead of var == false.
Use an else statement instead of checking the condition's opposite.
if (behind) {
//...
behind = false;
} else {
//...
behind = true;
}
3. **Define the boolean outside `while`.**
This also solves your problem because you don't "re-check" the variable.
Boolean behind = true;
while(statement){
if (behind){
do something;
behind = false;
}else{
do something else;
behind = true;
}
}
Define the boolean before the while block.
Boolean behind = true;
while(statement){
if (behind){
do something;
behind = false;
} else {
do something;
behind = true;
}
}

JAVA return unexpected boolean result from method

Why the following method always return false for the below value.
Do I confuse with somethings??
public boolean isTwoWay(Detail detail) {
return (detail.isExchange && detail.isTwoWay && !detail.isIVR);
}
which data contain following
detail.isExchange = true;
detail.isTwoWay = true;
detail.isIVR = false;
but it return false instead of true
The only way the method will return false is if one of your assumptions is wrong:
detail.isExchange = true;
detail.isTwoWat = true;
detail.isIVR = false;
Rest assured, this kind of oversight happens to programmers all the time, including the best of us.
Put a breakpoint where you receive false instead of your expected true, and verify your assumptions.
I have tried with that and its print true always.
boolean isExchange = true;
boolean isTwoWay = true;
boolean isIVR = false;
System.out.println(isExchange && isTwoWay && !isIVR);

More simple logic condition to check non-empty requirements

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

Is there a way to shorten a conditional that contains a bunch of boolean comparisons?

e.g
if("viewCategoryTree".equals(actionDetail)
|| "fromCut".equals(actionDetail)
|| "fromPaste".equals(actionDetail)
|| ("viewVendorCategory".equals(actionDetail))&&"viewCategoryTree".equals(vendorCategoryListForm.getActionOrigin())
|| ("viewVendorCategory".equals(actionDetail))&&"fromEdit".equals(vendorCategoryListForm.getActionOrigin())
|| "deleteSelectedItem".equals(actionDetail)
|| ("viewVendorCategory".equals(actionDetail))&&"fromLink".equals(vendorCategoryListForm.getActionOrigin())){
//do smth
}
I've tried something like this
if(check("deleteSelectedItem,viewCategoryTree,fromCut,fromPaste,{viewVendorCategory&&viewVendorCategory},{viewVendorCategory&&fromEdit},{viewVendorCategory&&fromLink}",actionDetail,actionOrigin)){
//do smth
}
public boolean check(String str, String ad, String ao){
String oneCmp = "";
String[] result = str.split(",");
ArrayList adList = new ArrayList();
ArrayList aoList = new ArrayList();
for (int i=0; i<result.length; i++){
oneCmp = result[i];
Matcher m = Pattern.compile("\\{([^}]*)\\}").matcher(oneCmp);
if(m.matches()){
m.find();
String agrp = m.group();
String[] groupresult = agrp.split("[\\W&&[^!]]+");
Boolean a = false;
Boolean b = false;
if(groupresult[0].startsWith("!")){
a = !groupresult[0].substring(1).equals(ad);
} else a = groupresult[0].equals(ad);
if(groupresult[1].startsWith("!")){
b = !groupresult[1].substring(1).equals(ao);
}else b = groupresult[1].equals(ao);
if(agrp.indexOf("&&")!=-1){
if(!(a && b))return false;
}
else if(agrp.indexOf("||")!=-1){
if(!(a || b))return false;
}
} else {
if(oneCmp.indexOf("^")==-1){
checklist(oneCmp,ad);
if(!checklist(oneCmp,ad))return false;
}else{
if(!checklist(oneCmp,ao))return false;
}
}
}
return false;
}
public boolean checklist(String str, String key){
if(str.startsWith("!")){
if(str.substring(1).equals(key))return false;
}else { if (!str.substring(1).equals(key)) return false;
}
}
return false;
}
is there a better way to do this ? thanks.
Move the check to a method that takes actionDetail as argument:
// Assumes vendorCategoryListForm is a member variable.
boolean check(String actionDetail) {
return ("viewCategoryTree".equals(actionDetail)
|| "fromCut".equals(actionDetail)
|| "fromPaste".equals(actionDetail)
|| (("viewVendorCategory".equals(actionDetail))
&&"viewCategoryTree".equals(vendorCategoryListForm.getActionOrigin()))
|| (("viewVendorCategory".equals(actionDetail))
&&"fromEdit".equals(vendorCategoryListForm.getActionOrigin()))
|| "deleteSelectedItem".equals(actionDetail)
|| (("viewVendorCategory".equals(actionDetail))
&&"fromLink".equals(vendorCategoryListForm.getActionOrigin())))
}
if (check(actionDetail)) {
// do this
}
How about creating an array of what you need to test against.
And then some code like this:
arrayOfStrings = ["viewCategoryTree", ...]
match = false
for elem in arrayOfStrings:
if elem == actionDetail:
match = true
break
The good thing about an array is that it is easily extensible: you can easily add/remove elements to it both statically and dynamically.
Also kindly look at this post
Language Agnostic Credits to Galwegian
See Flattening Arrow Code for help.
1. Replace conditions with guard clauses.
2. Decompose conditional blocks into seperate functions.
3. Convert negative checks into positive checks.
Honestly, that code is no more readable. I would better suggest to encapsulate that conditional check into some property for the type like if (control.IsApplicable) { // do smth }.
No matter either you parameterize by one or two arguments.
But I suppose better solution is to have an array of matches that could be tested against and if matched then return true.
I don't think you are going to improve on this without adding a bunch of complexity, both in terms of the notation that you use to express the conditions and the implementation of the "engine" that evaluates them.
The notation issue is that: while you may end up expressing the conditions in fewer characters, someone else reading your code has to figure out what that funky string literal really means.
Besides, anything clever you do could have an impact on performance. For instance, your attempt compiles and applies a regex multiple times for each call to check.
Stick with what you've got would be my advice.
if(isValidActionDetail(actionDetail)
|| (isValidActionDetail(actionDetail)
&& ("viewCategoryTree".equals(vendorCategoryListForm.getActionOrigin())
|| "fromEdit".equals(vendorCategoryListForm.getActionOrigin())
|| "fromLink".equals(vendorCategoryListForm.getActionOrigin())))){
//do smth
}
}
public static boolean isValidActionDetail (String actionDetail) {
return "viewCategoryTree".equals(actionDetail) || "fromCut".equals(actionDetail)
|| "fromPaste".equals(actionDetail) || "deleteSelectedItem".equals(actionDetail)
|| "viewVendorCategory".equals(actionDetail);
}
You can decompose in the above way, as the first step to refactoring your logic.

boolean recursion part 2

trying to write a boolean function that returns true if 'm' is a ancestor of the current class. 'm' is an ancestor if it is a mom or dad, or a ancestor of mom or dad.
will this get me there?
public boolean isAncestor(member m){
if (mom == m || dad == m){
return true;
}
else{
if(isAncestor(m.mom) || isAncestor(m.dad)){
return true;
}
}
return false;
}
thanks!
Yes, more or less. What if you get to a layer of the ancestry where mom or dad aren't known, and are null?
public boolean isAncestor(member m){
if (m == null)
return false;
if (mom.equals(m) || dad.equals(m))
return true;
else if(isAncestor(m.mom) || isAncestor(m.dad))
return true;
return false;
}
The logic will get you there, however one must take care with the equal signs.
In Java == compares for equality of instances. Odds are good that over time you will have two instances which are comparatively equal but exist in different instances. If your code has been written to prevent such a thing from occurring, then you don't need to change the == to .equals(...); but, if you didn't put in any safeguards to ensure only one instance of each "same" object exists, then you might want to change the comparison to .equals(...) and implement an custom "public boolean equals(Object other) {...}` method for the base "person" class.
If you're going to use recurrsion, you are going to need to have a stop condition. Does everyone have a mom or a dad? consider this:
public boolean isAncestor(Member m) {
// stop condition
if(this.mom == null && this.dad == null) return false;
// stop condition
if(this.mom == m || this.dad == m) return true;
// loop condition
return mom.isAncestor(m) || dad.isAncestor(m);
}
It might but it is not 100% correct. You should also check if mum and dad exist otherwise you might end up with NullPointerException.
Moreover the others are correct with the == usage, quite suspicious.
When does the recursion stop, if there is no relationship?
Actually, you need a way to know which two members you are comparing for relationship. You'll probably want to do something like this (untested):
/**
* #param m1 the member we want to get ancestry from
* #param m2 the member we presume is an ancestor
*/
public boolean isAncestor(member m1, member m2){
if (m1 == NULL || m2 == NULL) {
return false;
}
if (m1.isMom(m2) || m1.isDad(m2)){
return true;
}
else if(isAncestor(m1.mom, m2) || isAncestor(m1.dad, m2)) {
return true;
}
return false;
}
You'd need to write isMom and isDad to compare the relationship of m2 to m1.

Categories

Resources