How to reduce cognitive complexity in java code - java

Please advise how to reduce cognitive complexity on the below code
ids.add((row.getCell(11) != null) ? row.getCell(11).getStringCellValue() : "");

Add a method to hide the details, for example:
private String getCellValueOrDefault(Cell cell) {
if (cell == null) {
return "";
}
return cell.getStringValue();
}
Then use the method:
ids.add(getCellValueOrDefault(row.getCell(11));

You can use Optional:
ids.add(Optional
.ofNullable(row.getCell(11))
.map(cell -> cell.getStringCellValue())
.orElse("")
)
That way you don't need an extra method. If this is something that is needed at many places it is better to create a specific method for at as Andrew S remarked.

Related

Null check using Optional for By/BySelector

I want to re-write my null checking code, and use Optional instead.
public BySelector select(BySelector bySelector, Boolean value) {
return (bySelector == null) ? By.checkable(value) : bySelector.checkable(value);
}
The above is my original code. I have no idea how to replace to Optional. I've tried the following but it is not working. Please advise. Thank you.
public BySelector select(BySelector bySelector, Boolean value) {
return Optional.ofNullable(bySelector.checkable(value).orElse(By.checkable(value);
}
There is no need to use Optional in your case as it is less clear than your simple null check, but this is how I would do :
Optional.ofNullable(bySelector)
.map(x -> By.checkable(value))
.orElse(BySelector.checkable(value));
Maybe you want your method to return an optional, which makes more sense.

Is there an elegant way to initialize and return value of nullable field using Optional

I have a piece of code which returns value of one field, but also initializes it:
public Observable<Integer> asObservable() {
if (subject == null) {
subject = BehaviorSubject.createDefault(0);
}
return subject;
}
I'm trying to use Optional class to avoid if statement:
public Observable<Integer> asObservableWithOptional() {
Optional.ofNullable(subject)
.executeIfAbsent(() -> BehaviorSubject.createDefault(0));
return subject;
}
Hovewer I'm still not happy with this code. Is there a way to turn this methos into one with one statement only? Something similar to following won't work because subject have not been initialized during call to ofNullable factory method:
return Optional.ofNullable(subject)
.executeIfAbsent(() -> BehaviorSubject.createDefault(0))
.get();
Note: I'm not using original Java8 API, but aNNiMON port of this API https://github.com/aNNiMON/Lightweight-Stream-API.
How about
return subject = Optional.ofNullable(subject).orElseGet(() -> BehaviorSubject.createDefault(0));
of course, you can use a ternary conditional operator instead of creating an Optional just to discard it immediately:
return subject != null ? subject : (subject = BehaviorSubject.createDefault(0));
I would suggest something like this :
return (subject == null ? (subject = BehaviorSubject.createDefault(0)) : subject);

Best way to verify string is empty or null

i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both.
1) Below does not account for all spaces like in case of empty XML tag
return inputString==null || inputString.length()==0;
2) Below one takes care but trim can eat some performance + memory
return inputString==null || inputString.trim().length()==0;
3) Combining one and two can save some performance + memory (As Chris suggested in comments)
return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;
4) Converted to pattern matcher (invoked only when string is non zero length)
private static final Pattern p = Pattern.compile("\\s+");
return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();
5) Using libraries like -
Apache Commons (StringUtils.isBlank/isEmpty)
or Spring (StringUtils.isEmpty)
or Guava (Strings.isNullOrEmpty)
or any other option?
Useful method from Apache Commons:
org.apache.commons.lang.StringUtils.isBlank(String str)
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:
if(myString==null || myString.isEmpty()){
//do something
}
or if blank spaces need to be detected as well:
if(myString==null || myString.trim().isEmpty()){
//do something
}
you could easily wrap these into utility methods to be more concise since these are very common checks to make:
public final class StringUtils{
private StringUtils() { }
public static bool isNullOrEmpty(string s){
if(s==null || s.isEmpty()){
return true;
}
return false;
}
public static bool isNullOrWhiteSpace(string s){
if(s==null || s.trim().isEmpty()){
return true;
}
return false;
}
}
and then call these methods via:
if(StringUtils.isNullOrEmpty(myString)){...}
and
if(StringUtils.isNullOrWhiteSpace(myString)){...}
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>.
This one from Google Guava could check out "null and empty String" in the same time.
Strings.isNullOrEmpty("Your string.");
Add a dependency with Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
with Gradle
dependencies {
compile 'com.google.guava:guava:20.0'
}
Haven't seen any fully-native solutions, so here's one:
return str == null || str.chars().allMatch(Character::isWhitespace);
Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):
return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
Or, to be really optimal (but hecka ugly):
int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
One thing I like to do:
Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
Apache Commons Lang has StringUtils.isEmpty(String str) method which returns true if argument is empty or null
springframework library Check whether the given String is empty.
f(StringUtils.isEmpty(str)) {
//.... String is blank or null
}
Optional.ofNullable(label)
.map(String::trim)
.map(string -> !label.isEmpty)
.orElse(false)
OR
TextUtils.isNotBlank(label);
the last solution will check if not null and trimm the str at the same time
In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.
Take an example where I have an input object which was converted into string using String.valueOf(obj) API. In case obj reference is null, String.valueOf returns "null" instead of null.
When you attempt to use, StringUtils.isBlank("null"), API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.
Simply and clearly:
if (str == null || str.trim().length() == 0) {
// str is empty
}
With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces
import jdk.internal.joptsimple.internal.Strings;
...
String targetString;
if (Strings.isNullOrEmpty(tragetString)) {}
You can make use of Optional and Apache commons Stringutils library
Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);
here it will check if the string1 is not null and not empty else it will return string2
If you have to test more than one string in the same validation, you can do something like this:
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class StringHelper {
public static Boolean hasBlank(String ... strings) {
Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();
return Optional
.ofNullable(strings)
.map(Stream::of)
.map(stream -> stream.anyMatch(isBlank))
.orElse(false);
}
}
So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.
We can make use of below
Optional.ofNullable(result).filter(res -> StringUtils.isNotEmpty(res))
.ifPresent( s-> val.set(s));

Check if returned value is not null and if so assign it, in one line, with one method call

Java is littered with statements like:
if(cage.getChicken() != null) {
dinner = cage.getChicken();
} else {
dinner = getFreeRangeChicken();
}
Which takes two calls to getChicken() before the returned object can be assigned to dinner.
This could also be written in one line like so:
dinner = cage.getChicken() != null? cage.getChicken() : getFreeRangeChicken();
But alas there are still two calls to getChicken().
Of course we could assign a local variable then use the ternary operator again to assign it if it is not null, but this is two lines and not so pretty:
FutureMeal chicken = cage.getChicken();
dinner = chicken != null? chicken : getFreeRangeChicken();
So is there any way to say:
Variable var = some value if some value is not null OR some other
value;
And I guess I'm just talking syntax here, after the code is compiled it probably doesn't make much difference how the code was written in a performance sense.
As this is such common code it'd be great to have a one-liner to write it.
Do any other languages have this feature?
Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.
dinner = Optional.ofNullable(cage.getChicken())
.orElse(getFreerangeChicken());
Note: This usage of Optional is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
Since Java 9 you have Objects#requireNonNullElse which does:
public static <T> T requireNonNullElse(T obj, T defaultObj) {
return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}
Your code would be
dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());
Which is 1 line and calls getChicken() only once, so both requirements are satisfied.
Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.
Consider also the alternative Objects#requireNonNullElseGet:
public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.
If you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull
Your code would be:
dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.
Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.
Use your own
public static <T> T defaultWhenNull(#Nullable T object, #NonNull T def) {
return (object == null) ? def : object;
}
Example:
defaultWhenNull(getNullableString(), "");
Advantages
Works if you don't develop in Java8
Works for android development with support for pre API 24 devices
Doesn't need an external library
Disadvantages
Always evaluates the default value (as oposed to cond ? nonNull() : notEvaluated())
This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).
By the way, you encounter the same disadvantage when using Optional.orElse() ;-)
You could use
Objects.requireNonNullElse(cage.getChicken(), getFreerangeChicken())
even nicer with static import:
import static java.util.Objects.requireNonNullElse;
requireNonNullElse(cage.getChicken(), getFreerangeChicken())
dinner = cage.getChicken();
if(dinner == null) dinner = getFreeRangeChicken();
or
if( (dinner = cage.getChicken() ) == null) dinner = getFreeRangeChicken();
Alternatively in Java8 you can use Nullable or NotNull Annotations according to your need.
public class TestingNullable {
#Nullable
public Color nullableMethod(){
//some code here
return color;
}
public void usingNullableMethod(){
// some code
Color color = nullableMethod();
// Introducing assurance of not-null resolves the problem
if (color != null) {
color.toString();
}
}
}
public class TestingNullable {
public void foo(#NotNull Object param){
//some code here
}
...
public void callingNotNullMethod() {
//some code here
// the parameter value according to the explicit contract
// cannot be null
foo(null);
}
}
http://mindprod.com/jgloss/atnullable.html

Groovy - condense multiple if statements

I'm a groovy newbie so bear with me here. I love groovy's power to write less and often cleaner code but I'm trying to figure out if there's a better or more readable way of condensing these multiple if statements. It's a fairly straightforward code snippet but there's got to be a better way of doing this. I'm a newbie so any code snippets are greatly appreciated.
if (!textOverlay) {
textType = ""
if(url != null){
Page getPage = resource.getResourceResolver().getResource(url).adaptTo(Page.class)
if (getPage != null) {
showLink = showLink + ".html"
if (fragment.length() > 0) {
url += "#"+fragment;
}
}
}
} else {
//do something else
}
Thanks in advance for the help!
This doesn't help with nesting, but there are a few places where you could take advantage of Groovy to make the code a bit more compact. I've added some explanatory comments
if (!textOverlay) {
textType = ""
// null is considered false, so no need to explicitly check for null
if (url) {
// getResourceResolver() replaced by resourceResolver
// Page and Page.class are the same thing
Page getPage = resource.resourceResolver.getResource(url).adaptTo(Page)
// Groovy truth
if (getPage) {
// use String concatenation operator (also works in Java)
showLink += ".html"
// non-empty strings evaluate to true
if (fragment) {
// GString instead of string concatenation
url += "#$fragment"
}
}
}
} else {
//do something else
}

Categories