Needed assistance with a java recursive method, described below - java

I have an object that has operands and predicates inside.
I have the following model:
operand[0] - predicates = NULL
- operands[0] - predicates = NULL
- operands[0] - operands = NULL
- predicates[0] - tableVal="val1.aaa"
- predicates[1] - tableVal="val.bbb"
- predicates[2] = tableVal="val5.ccc"
- operands[1] - operands = NULL
- predicates[0] - tableVal="val3.asd"
- predicates[1] - tableVal="val2.ccc"
I'm looking for a certain value, that contains "bbb" and I need a recursive method to get through the whole structure until it finds the predicate with the tableVal containing "bbb".
I tried something like this:
private String searchInsideStructure(Object obj, int indexOperands) {
if (null != obj.predicates) {
indexPredicates = 0;
while(obj.predicates.length > indexPredicates) {
if(predicates[indexPredicates].tableVal.contains("bbb")) {
return tableVal;
}
indexPredicates++;
}
}
if (null != obj.operands) {
while (indexOperands < obj.operands.length) {
searchInsideStructure(obj.operands[indexOperands], indexOperands);
indexOperands++;
}
}
return null;
}
.................
indexOperands = 0;
searchedField = searchInsideStructure(initialObj, indexOperands);
if (null != searchedField) {
return searchedField
}
But it returns null. How can I change this recursive method to go through the operands, while finding predicates and finds in predicates the desired tableVal ("val.bbb" in this example)??? Thanks!

There's 2 fixes to consider:
In the second while loop, you should verify the result of searchInsideStructure, and propagate it if not null
You should avoid propagating indexOperands because it will make you skip some predicates when testing. You can then just use a for(each) loop to browse predicates.

Related

How to apply continue and yield multiple values from a for-loop in scala?

I am trying to convert a module of a java program into Scala. So far, I have been able to apply Scala's functional programming paradigm and its syntax in every module I converted. But I have come across a method that does some validations, use continue and finally yield the output.
Below is the code in Java:
public boolean checkColumn(String server, String database, String schema, String table, String column) {
boolean bServer, bDatabase, bSchema, bTable, bColumn, bRet = false;
for (int i = 0; i < columns.length; i++) {
if ((server == null) || (server.length() == 0)) {
bServer = true;
} else {
bServer = columns[i][0].equalsIgnoreCase(server);
}
if (!bServer) continue;
if ((database == null) || (database.length() == 0)) {
bDatabase = true;
} else {
bDatabase = columns[i][1].equalsIgnoreCase(database);
}
if (!bDatabase) continue;
if ((schema == null) || (schema.length() == 0)) {
bSchema = true;
} else {
bSchema = columns[i][2].equalsIgnoreCase(schema);
}
if (!bSchema) continue;
bTable = columns[i][3].equalsIgnoreCase(table);
if (!bTable) continue;
bColumn = columns[i][4].equalsIgnoreCase(column);
if (!bColumn) continue;
bRet = true;
break;
}
return bRet;
}
While I understand there is no continue in recent versions of Scala I am able to understand how to write the same code in Scala. I tried to construct a for loop as below:
val finalReturn = for {i <- 0 until columns.length
} yield bRet
But couldn't think of a way to form the logic of all the if-conditions & continue inside the for-loop. Could anyone let me know how can I write the same code in Scala ?
You are checking that (at least) one of the columns matches all the tests. This is the exists operation:
def checkColumn(server: String, database: String, schema: String, table: String, column: String) = {
columns.exists { col =>
(server.isEmpty || col(0).equalsIgnoreCase(server)) &&
(database.isEmpty || col(1).equalsIgnoreCase(database)) &&
(schema.isEmpty || col(2).equalsIgnoreCase(schema)) &&
col(3).equalsIgnoreCase(table) &&
col(4).equalsIgnoreCase(column)
}
This will check each element in turn until one of the columns passes all the tests (which will return true) or the list is exhausted, which will return false.
There is no way to write exactly the same algorithm with a functional approach because in java code this is a very imperative style with mutability and manual control over the flow of evaluation.
So you should think what this code does, what is the logic in the code. And then implement this logic with functional primitives and patterns.
Let's go step by step
if ((server == null) || (server.length() == 0)) {
bServer = true;
} else {
bServer = columns[i][0].equalsIgnoreCase(server);
}
if (!bServer) continue;
it checks that if there is the defined server string - you should check that 1st field of the column
should be equal to that defined server string (i don't know what columns exactly are, but I try to guess that columns[i] is column and column[j] is a field of the column).
Otherway it calls continue and skips the iteration.
Same for other fields with the exception that table and schema doesn't being checked for emptiness.
If we looked at the end, the skipping results in "not setting bRet to true". So if all checks passed for some column, bRet would be true and the loop breaks after that.
So we can say that "if there exists at least one column that passes the checks - the result of that method should be true". Good for you that in scala you have a special method of the collection exists with exactly that logic.
Also, it is better to have a dedicated helper function to deal with nullability and emptiness.
private def isEmpty(string: String) = string == null || string.isEmpty
def checkColumn(server: String, database: String, schema: String, table: String, column: String): Boolean = {
columns.exists { column =>
(isEmpty(server) || column(0).equalsIgnoreCase(server)) &&
(isEmpty(database) || column(1).equalsIgnoreCase(database)) &&
(isEmpty(schema) || column(2).equalsIgnoreCase(schema)) &&
column(3).equalsIgnoreCase(table) &&
column(4).equalsIgnoreCase(column)
}
}
In addition, I have to mention that in Scala dealing with nulls in business code is very bad practice, you should change nullable parameters to Option[String] and change a little bit expressions to deal with that type. I will show 3 ways of doing that:
def checkColumn(serverOpt: Option[String], databaseOpt: Option[String], schemaOpt: Option[String], String table, String column): Boolean =
columns.exists { column =>
serverOpt.filterNot(_.isEmpty).map(server => column(0).equalsIgnoreCase(server).getOrElse(true) &&
databaseOpt.filterNot(_.isEmpty).map(column(1).equalsIgnoreCase).getOrElse(true) &&
schemaOpt.filterNot(_.isEmpty).fold(true)(column(2).equalsIgnoreCase)&&
column(3).equalsIgnoreCase(table) &&
column(4).equalsIgnoreCase(column)
}
And when you call it, you should wrap your nullable strings with Option constructor like this:
checkColumn(Option(nullableServer), Option(nullableDatabase), Option(nullableshema), table, column)
Further improvements would be to use refinement types techniques and change the type of nullable and maybe empty strings from just Option[String] to Option[NonEmptyString].

Java Optional if object is not null - returns the method result, if null - returns default value

Is it possible to transform this code to a Java 8 Optional one-line expression?
long lastPollTime;
if (object != null) {
lastPollTime = object.getTime();
} else {
lastPollTime = 0;
}
i.e. if some object is not null, I need to call an object method and return its result, or else return 0.
Optional.ofNullable().orElse() is not suitable, as it returns the object of the same type, but i need the result of the method call or some default value.
A few forms:
long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);
long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);
long lastPollTime = Optional.ofNullable(object).isPresent() ? object.getTime() : 0;
long lastPollTime = object != null ? object.getTime() : 0;
Of these, the last one, which doesn't use Optional (and therefore doesn't strictly answer your question!) is simpler to read and has fewer runtime overheads, and so should be preferred.
Arguably, it's even simpler if you reverse the options:
long lastPollTime = object == null ? 0 : object.getTime();
... although you might prefer to have the default last -- it's a matter of personal taste.
If you really can't use ternary operators, and you're doing this a lot, you could write your own utility method:
public <T,U> U mapWithFallback(T obj, Function<T,U> function, U fallback) {
if(obj == null) {
return fallback;
} else {
return function.apply(obj);
}
}
... callable as:
long lastPollTime = mapWithFallback(object, o -> o.getTime(), 0);
... or make a complete mockery of your no-ternaries check using:
public <T,U> U ifElse( Supplier<Boolean> a, Supplier<U> ifTrue, Supplier<U> ifFalse) {
if(a.get()) {
return ifTrue.get();
} else {
return ifFalse.get();
}
}
long lastPollTime = ifElse( () -> object == null, () -> object.getTime(), () -> 0);
It's in even better taste to avoid null references altogether, so that this kind of check isn't needed -- for example using the Null Object pattern.
... or by writing methods that return Optional rather than potential nulls. Optional is a great class; use it. Just don't convert something to Optional purely so you can immediately check whether it's empty.
long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);
long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);
Instead of o -> o.getTime() you could use a methods reference like ClassOfObject::getTime
long lastPollTime = object != null ?object.getTime():0;
you can do like below with java 8
long lastPollTime=Optional.ofNullable(object).isPresent()?object.getTime():0;
or without using java8 like this
long lastPollTime = object != null ?object.getTime():0;
Re ternary vs optional, if you ever needed to nest them the optional ends up being easier to read
long lastPollTime = Optional.ofNullable(object1)
.map(o -> o.getTime())
.orElse(Optional.ofNullable(object2)
.map(o -> o.getTime())
.orElse(0));

checking and setting variable, efficiently

I am new to programming and have a simple question: is there a "better" or more efficient way of doing this...
if (x != 0) {
y = x;
}
or
if (getMethod() != null) {
value = getMethod();
}
I'm new to programming and above code (esp the 2nd one) seems inefficient.
Thanks in advance.
You second example can suffer from a "Time of check, to time of use" weakness. If the first invocation of getMethod() returns non-null, it is possible that your second invocation will return null. A better way to do it would be:
value = getMethod();
if(NULL != value)
{
/* use value as planned */
}
else
{
/* handle a null value, probably an error */
}
if interested, you can read more about TOCTTOU weaknesses here.
For your first example, I don't really see a better way of doing this.
N.B. This answer is from the perspective of a C programmer (seeing as how C was one of your tags).
Hope this helps
- T.
You can make it shorter
if ( x ) y = x;
is the same as
if (x != 0) {
y = x;
}
And
if ( getMethod() ) value = getMethod();
is the same as
if (getMethod() != null) {
value = getMethod();
}
First code snippet:
In C any non-zero value is treated as true and 0 treated as false. So, for the first example, you can rewrite it as:
if (x) {
y = x; // this line will be executed if x not equal to zero
}
Second code snippet:
You called getMethod() twice which is not efficient. As per your code, you are assigning the return value of getMethod() into value if getMethod() returns anything but NULL. So you can use a temporary variable to check the return value of getMethod(), like following:
temp = getMethod();
if (temp != null) {
value = temp;
}
That will reduce calling same method twice.

Avoid NoSuchElementException with Stream

I have the following Stream:
Stream<T> stream = stream();
T result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst().get();
return result;
However, there is not always a result which gives me the following error:
NoSuchElementException: No value present
So how can I return a null if there is no value present?
You can use Optional.orElse, it's much simpler than checking isPresent:
T result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst().orElse(null);
return result;
Stream#findFirst() returns an Optional which exists specifically so that you don't need to operate on null values.
A container object which may or may not contain a non-null value. If a
value is present, isPresent() will return true and get() will return
the value.
Otherwise, Optional#get() throws a NoSuchElementException.
If a value is present in this Optional, returns the value, otherwise
throws NoSuchElementException.
An Optional will never expose its value if it is null.
If you really have to, just check isPresent() and return null yourself.
Stream<T> stream = stream();
Optional<T> result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst();
if (result.isPresent())
return result.get();
return null;
An alternate method for replacing the Optional.get (which more likely than not fails the user's intentions with a NoSuchElementException) is with a more verbose API introduced in JDK10 termed as Optional.orElseThrow(). In author's words -
Optional.get() is an "attractive nuisance" and is too tempting for
programmers, leading to frequent errors. People don't expect a getter
to throw an exception. A replacement API for Optional.get() with
equivalent semantics should be added.
Note :- The underlying implementation of both these APIs is same, yet the latter reads out more clearly that a NoSuchElementException would be thrown by default if the value is not present which inlines to the existing Optional.orElseThrow​(Supplier<? extends X> exceptionSupplier) implementation used by consumers as an explicit alternate.
If you wish to continue using the object and not throw any exception, then
Optional.isPresent(object)
is the way to go

Java: avoid checking for null in nested classes (Deep Null checking)

Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.
So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
No, can't change the structure. It's from a service I don't have control over.
No, I can't use Groovy and it's handy "Elvis" operator.
No, I'd prefer not to wait for Java 8 :D
I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.
You can use for:
product.getLatestVersion().getProductData().getTradeItem().getInformationProviderOfTradeItem().getGln();
optional equivalent:
Optional.ofNullable(product).map(
Product::getLatestVersion
).map(
ProductVersion::getProductData
).map(
ProductData::getTradeItem
).map(
TradeItemType::getInformationProviderOfTradeItem
).map(
PartyInRoleType::getGln
).orElse(null);
Your code behaves the same as
if(family != null &&
family.getPeople() != null &&
family.people.get(0) != null &&
family.people.get(0).getAddress() != null &&
family.people.get(0).getAddress().getPostalCode() != null) {
//My Code
}
Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.
If, in case, you are using java8 then you may use;
resolve(() -> people.get(0).getAddress().getPostalCode());
.ifPresent(System.out::println);
:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
REF: avoid null checks
The closest you can get is to take advantage of the short-cut rules in conditionals:
if(family != null && family.getPeople() != null && family.people.get(0) != null && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
By the way, catching an exception instead of testing the condition in advance is a horrible idea.
I personally prefer something similar to:
nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))
public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
try {
function.apply(supplier.get());
} catch (NullPointerException n) {
return null;
}
}
or something like
nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())
public static <T> T nullSafeGetter(Supplier<T> supplier) {
try {
return supplier.get();
} catch (NullPointerException n) {
return null;
}
}
Best part is the static methods are reusable with any function :)
You can get rid of all those null checks by utilizing the Java 8 Optional type.
The stream method - map() accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the neath.
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
We also have another option to achieve the same behavior is by utilizing a supplier function to resolve the nested path:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
How to invoke new method? Look below:
Outer obj = new Outer();
obj.setNested(new Nested());
obj.getNested().setInner(new Inner());
resolve(() -> obj.getNested().getInner().getFoo())
.ifPresent(System.out::println);
Instead of using null, you could use some version of the "null object" design pattern. For example:
public class Family {
private final PersonList people;
public Family(PersonList people) {
this.people = people;
}
public PersonList getPeople() {
if (people == null) {
return PersonList.NULL;
}
return people;
}
public boolean isNull() {
return false;
}
public static Family NULL = new Family(PersonList.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
import java.util.ArrayList;
public class PersonList extends ArrayList<Person> {
#Override
public Person get(int index) {
Person person = null;
try {
person = super.get(index);
} catch (ArrayIndexOutOfBoundsException e) {
return Person.NULL;
}
if (person == null) {
return Person.NULL;
} else {
return person;
}
}
//... more List methods go here ...
public boolean isNull() {
return false;
}
public static PersonList NULL = new PersonList() {
#Override
public boolean isNull() {
return true;
}
};
}
public class Person {
private Address address;
public Person(Address address) {
this.address = address;
}
public Address getAddress() {
if (address == null) {
return Address.NULL;
}
return address;
}
public boolean isNull() {
return false;
}
public static Person NULL = new Person(Address.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
etc etc etc
Then your if statement can become:
if (!family.getPeople().get(0).getAddress().getPostalCode.isNull()) {...}
It's suboptimal since:
You're stuck making NULL objects for every class,
It's hard to make these objects generic, so you're stuck making a null-object version of each List, Map, etc that you want to use, and
There are potentially some funny issues with subclassing and which NULL to use.
But if you really hate your == nulls, this is a way out.
Although this post is almost five years old, I might have another solution to the age old question of how to handle NullPointerExceptions.
In a nutshell:
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
}
Since there is a lot of legacy code still in use, using Java 8 and Optional isn't always an option.
Whenever there are deeply nested classes involved (JAXB, SOAP, JSON, you name it...) and Law of Demeter isn't applied, you basically have to check everything and see if there are possible NPEs lurking around.
My proposed solution strives for readibility and shouldn't be used if there aren't at least 3 or more nested classes involved (when I say nested, I don't mean Nested classes in the formal context). Since code is read more than it is written, a quick glance to the left part of the code will make its meaning more clear than using deeply nested if-else statements.
If you need the else part, you can use this pattern:
boolean prematureEnd = true;
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
prematureEnd = false;
}
if(prematureEnd) {
System.out.println("The else part");
}
Certain IDEs will break this formatting, unless you instruct them not to (see this question).
Your conditionals must be inverted - you tell the code when it should break, not when it should continue.
One more thing - your code is still prone to breakage. You must use if(family.getPeople() != null && !family.getPeople().isEmpty()) as the first line in your code, otherwise an empty list will throw a NPE.
If you can use groovy for mapping it will clean up the syntax and codes looks cleaner. As Groovy co-exist with java you can leverage groovy for doing the mapping.
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
instead you can do this
if(family?.people?[0]?.address?.postalCode) {
//do something
}
or if you need to map it to other object
somobject.zip = family?.people?[0]?.address?.postalCode
Not such a cool idea, but how about catching the exception:
try
{
PostalCode pc = people.get(0).getAddress().getPostalCode();
}
catch(NullPointerException ex)
{
System.out.println("Gotcha");
}
If it is rare you could ignore the null checks and rely on NullPointerException. "Rare" due to possible performance problem (depends, usually will fill in stack trace which can be expensive).
Other than that 1) a specific helper method that checks for null to clean up that code or 2) Make generic approach using reflection and a string like:
checkNonNull(family, "people[0].address.postalcode")
Implementation left as an exercise.
I was just looking for the same thing (my context: a bunch of automatically created JAXB classes, and somehow I have these long daisy-chains of .getFoo().getBar().... Invariably, once in a while one of the calls in the middle return null, causing NPE.
Something I started fiddling with a while back is based on reflection. I'm sure we can make this prettier and more efficient (caching the reflection, for one thing, and also defining "magic" methods such as ._all to automatically iterate on all the elements of a collection, if some method in the middle returns a collection). Not pretty, but perhaps somebody could tell us if there is already something better out there:
/**
* Using {#link java.lang.reflect.Method}, apply the given methods (in daisy-chain fashion)
* to the array of Objects x.
*
* <p>For example, imagine that you'd like to express:
*
* <pre><code>
* Fubar[] out = new Fubar[x.length];
* for (int i=0; {#code i<x.length}; i++) {
* out[i] = x[i].getFoo().getBar().getFubar();
* }
* </code></pre>
*
* Unfortunately, the correct code that checks for nulls at every level of the
* daisy-chain becomes a bit convoluted.
*
* <p>So instead, this method does it all (checks included) in one call:
* <pre><code>
* Fubar[] out = apply(new Fubar[0], x, "getFoo", "getBar", "getFubar");
* </code></pre>
*
* <p>The cost, of course, is that it uses Reflection, which is slower than
* direct calls to the methods.
* #param type the type of the expected result
* #param x the array of Objects
* #param methods the methods to apply
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T[] apply(T[] type, Object[] x, String...methods) {
int n = x.length;
try {
for (String methodName : methods) {
Object[] out = new Object[n];
for (int i=0; i<n; i++) {
Object o = x[i];
if (o != null) {
Method method = o.getClass().getMethod(methodName);
Object sub = method.invoke(o);
out[i] = sub;
}
}
x = out;
}
T[] result = (T[])Array.newInstance(type.getClass().getComponentType(), n);
for (int i=0; i<n; i++) {
result[i] = (T)x[i];
}
return result;
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
and my favorite, the simple try/catch, to avoid nested null checks...
try {
if(order.getFulfillmentGroups().get(0).getAddress().getPostalCode() != null) {
// your code
}
} catch(NullPointerException|IndexOutOfBoundsException e) {}

Categories

Resources