Most efficient way to prevent an infinite recursion in toString()? - java

To string on a collection can get into a infinite loop if somewhere in the graph of collected items is a reference back to itself. See example below.
Yes, good coding practices should prevent this in the first place, but anyway, my question is: What is the most efficient way to detect a recursion in this situation?
One approach is to use a set in a threadlocal, but that seems a bit heavy.
public class AntiRecusionList<E> extends ArrayList<E> {
#Override
public String toString() {
if ( /* ???? test if "this" has been seen before */ ) {
return "{skipping recursion}";
} else {
return super.toString();
}
}
}
public class AntiRecusionListTest {
#Test
public void testToString() throws Exception {
AntiRecusionList<AntiRecusionList> list1 = new AntiRecusionList<>();
AntiRecusionList<AntiRecusionList> list2 = new AntiRecusionList<>();
list2.add(list1);
list1.add(list2);
list1.toString(); //BOOM !
}
}

When I have to iterate over risky graphs, I usually make a function with a decrementing counter.
For example :
public String toString(int dec) {
if ( dec<=0 ) {
return "{skipping recursion}";
} else {
return super.toString(dec-1);
}
}
public String toString() {
return toString(100);
}
I won't insist on it, as you already know it, but that doesn't respect the contract of toString() which has to be short and predictable.

The threadlocal bit I mentioned in the question:
public class AntiRecusionList<E> extends ArrayList<E> {
private final ThreadLocal<IdentityHashMap<AntiRecusionList<E>, ?>> fToStringChecker =
new ThreadLocal<IdentityHashMap<AntiRecusionList<E>, ?>>() {
#Override
protected IdentityHashMap<AntiRecusionList<E>, ?> initialValue() {
return new IdentityHashMap<>();
}
};
#Override
public String toString() {
boolean entry = fToStringChecker.get().size() == 0;
try {
if (fToStringChecker.get().containsKey(this)/* test if "this" has been seen before */) {
return "{skipping recursion}";
} else {
fToStringChecker.get().put(this, null);
entry = true;
}
return super.toString();
} finally {
if (entry)
fToStringChecker.get().clear();
}
}
}

You can create toString which takes an identity hash set.
public String toString() {
return toString(Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()));
}
private String toString(Set<Object> seen) {
if (seen.add(this)) {
// to string this
} else {
return "{this}";
}
}

I recommend using ToStringBuilder from Apache Commons Lang. Internally it uses a ThreadLocal Map to "detect cyclical object references and avoid infinite loops."

The problem is not inherent to collections, it can happen with any graph of objects that have cyclic references, e.g., a doubly-linked list.
I think that a sane policy is: the toString() method of your class should not call toString() of its children/referenced if there is a possibility that it's part of a object graph with cycles. Elsewhere, we could have a special methods (perhaps static, perhaps as an auxiliary class) that produces a string representation of the full graph.

You could always keep track of recursion as follows (no threading issues taken into account):
public static class AntiRecusionList<E> extends ArrayList<E> {
private boolean recursion = false;
#Override
public String toString() {
if(recursion){
//Recursion's base case. Just return immediatelly with an empty string
return "";
}
recursion = true;//start a perhaps recursive call
String result = super.toString();
recursion = false;//recursive call ended
return result;
}
}

The simplest way: don't call toString() on the elements of a collection or a map, ever. Just print a [] to indicate that it's a collection or map, and avoid iterating over it entirely. It's the only bullet-proof way to avoid falling in an infinite recursion.
In the general case, you can't anticipate what elements are going to be in a Collection or Map inside another object, and the dependency graph could be quite complex, leading to unexpected situations where a cycle occurs in the object graph.
What IDE are you using? because in Eclipse there's an option to explicitly handle this case when generating the toString() method via the code generators - that's what I use, when an attribute happens to be a non-null collection or map print [] regardless of how many elements it contains.

If you want to go overboard, you could use an aspect that tracks nested collections whenever you call toString().
public aspect ToStringTracker() {
Stack collections = new Stack();
around( java.util.Collection c ): call(String java.util.Collection+.toString()) && target(c) {
if (collections.contains(c)) { return "recursion"; }
else {
collections.push(c);
String r = c.toString();
collections.pop();
return r;
}
}
}
I'm never 100% on syntax without throwing this into Eclipse, but I think you get the idea

maybe you could create an Exception in your toString and leverage on the stacktrace to know where you are in the stack, and you would find it there are recursive calls.
Some framework does this way.
#Override
public String toString() {
// ...
Exception exception = new Exception();
StackTraceElement[] stackTrace = exception.getStackTrace();
// now you analyze the array: stack trace elements have
// 4 properties: check className, lineNumber and methodName.
// if analyzing the array you find recursion you stop propagating the calls
// and your stack won't explode
//...
}

Related

An implementation of Optional for empty Strings

One of the best things about Optional is it saves all the boilerplate checking for null values in a long chain:
Optional.ofNullable(myService.getSomething())
.map(secondService::fetch)
.map(thirdService::fetchAgain)
// And so forth...
At any point the Optional will jump onto the 'empty' track if map returns a null.
It would be great if something similar could be done for Strings instead of having to check them for String::isEmpty every time:
Optional.ofNullable(entity.getName())
.filter(String::isEmpty)
.map(Utils::performSomeOperation)
.filter(String::isEmpty)
.or(service::getMostCommonName)
.filter(String::isEmpty)
.orElse("Bob");
Something like this:
OptionalString.ofEmptyable(entity.getName())
.map(Utils::performSomeOperation)
.or(service::getMostCommonName)
.orElse("Bob");
The key logic in Optional happens in ofNullable when it calls its check for value == null. Theoretically you could apply any sort of logic in there:
MagicalOptionalString(StringUtils::isNotBlank).ofEmptyable(entity.getName())
.map(Utils::performSomeOperation)
.or(service::getMostCommonName)
.orElse("Bob");
However, Optional is final, preventing any straightforward way of extending this behaviour. So is there an existing, robust implementation of this out there already?
Trying out a few things to resolve what you were aiming at, and realizing that I would second the thought from VGR as implementing such a use case is a lot of extra work as compared to using the existing methods.
Yet, few details that I could add to after spending some time looking over the implementations -
As a utility, you could implement a static implementation which verifies for both null and isEmpty condition for a string input and returns Optional accordingly. The code could look something like -
private static Optional<String> ofEmptyable(String string) {
return isNullOrEmpty(string) ? Optional.empty() : Optional.of(string);
}
private static boolean isNullOrEmpty(String target) {
return target == null || target.isEmpty();
}
this could then replace the usage of the ofNullable which specifically checks for null(the primary purpose of Optional).
Since the expectations in your problem statement were to actually handle the cases per method(map/or/orElse) call as in the optional, one approach similar to OptionalInt could be to implement a custom OptionalString as -
public final class OptionalString {
private static final OptionalString EMPTY = new OptionalString();
private final boolean isPresent;
private final String value;
private OptionalString() {
this.isPresent = false;
this.value = "";
}
private static OptionalString empty() {
return EMPTY;
}
private boolean isPresent() {
return isPresent;
}
private OptionalString(String value) {
this.isPresent = true;
this.value = value;
}
public static OptionalString of(String value) {
return value == null || value.isEmpty() ? OptionalString.empty() : new OptionalString(value);
}
public OptionalString map(Function<? super String, ? extends String> mapper) {
return !isPresent() ? OptionalString.empty() : OptionalString.of(mapper.apply(this.value));
}
public OptionalString or(Supplier<String> supplier) {
return isPresent() ? this : OptionalString.of(supplier.get());
}
String orElse(String other) {
return isPresent ? value : other;
}
public String getAsString() {
return Optional.of(value).orElseThrow(() -> new NoSuchElementException("No value present"));
}
}
which could be further implemented for your use case in the following manner -
String customImpl = OptionalString.of(entity.getName())
.map(OptionalStringTest::trimWhiteSpaces) // OptionalStringTest is my test class name where 'trimWhiteSpaces' operation on String resides
.or(service::getMostCommonName)
.orElse("learning");
System.out.println(String.format("custom implementation - %s", customImpl));
where
private static String trimWhiteSpaces(String x) {
return x.trim();
}
Note - Honestly, I couldn't find the rationale behind not having an OptionalString class upfront in the JDK (the reason why I am stating this is because I suspect there definitely must have been a thought behind it), I believe its just that the radius of my reach is much smaller and I would expect someone credible to add to the details here. IMHO, it seems more like almost all of what you desire is right there using the Optional<String> and which takes us back to the starting of the loop.
For anyone working in Kotlin, this is really easy to do:
class NonEmptyString private constructor(val Email: String) {
companion object Factory {
operator fun invoke(value: String?): T? = value?.let { if (it.isNotEmpty()) NonEmptyString(value) else null }
}
}
The "static" invoke function conditionally creates a new object depending on whether it's valid or not. And allows you to call it like a constructor (NonEmptyString(value)). The private constructor forces you to use the invoke method.
Because this returns a null if it's not valid, and Kotlin has null-safety built in, it can be really easy to chain. Adding map or flatMap functions is then pretty straight-forward.
See this Code Review question for a more comprehensive, generalisable example I wrote.

Homemade Stack Equals method

For my data structures class, we have to create our own Stack data type and the implementation for it as a project. The problem I'm running into is when the professor asked us to implement an equals(Object object) method. Heres what I have so far...
package stack;
import list.*;
public class Stack <E>
implements StackADT<E>//the interface
{
List <E> values;
public Stack()
{
values = new ArrayList<E>();
}
public E push(E value)
{
values.add(value);
return value;
}
public E pop()
{
return values.remove(values.size()-1);
}
public E peek()
{
return values.get(values.size()-1);
}
/** #return true only if this Stack is empty */
public boolean isEmpty()
{
return (values.size()==0);
}
/** Clear this stack, to make it an empty stack */
public void clear()
{
for (int i = 0; i < values.size()-1; i++)
{
pop();
}
}
public String toString()
{
String result = "[";
for (int i = 0; i<values.size(); i++)
{
if (i == values.size()-1)
{
result = result + values.get(i);
}
else
{
result = result + values.get(i) +",";
}
}
result = result + "]";
return result;
}
public boolean equals (Object object)
{
if (!(object instanceof StackADT))
{
return false;
}
StackADT <E> otherStack = new Stack<E>();
for(Object o: object)//heres where i run into trouble
{
otherStack.push(o);
}
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
}
Our Stack is pretty much an ArrayList which we also built in our class. the problem is, I cant add the Object object into a stack because its not something thats iteratable(?able to be iterated over). Is there a better way to do this? I would think a get() would work, since the Stack I create is an ArrayList, but whenever I use get() on otherStack, it can't find the method. I had a temporary solution when I tried casting object as a stack(I hope im using the right terminology). It looked something like this
Stack otherStack = (Stack) object;
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
this seemed to work, but when pop() was called on otherStack, the values in the original list(the one that becomes otherStack) that was passed into the equals() method we're also popped from the original list, leading to an incorrect result. Is there a better way to do this without adding in any other methods? I'm trying to stick as close to the formula set up by my professor as possible, so I dont want to add any extra fields or methods.
any and all help is appreciated
An equals method is not supposed to create anything, not even a temporary object. Rather than creating a new otherStack, cast the object that you have checked to be StackADT, like this:
// This should be the first line of any equals() implementation:
if (object == this) {
return true;
}
// You've got this part right: you need to check the other object's type
if (!(object instanceof StackADT)) {
return false;
}
// Now that you know the type, cast the other object to StackADT<E>
StackADT<E> otherStack = (StackADT<E>)object;
// The next step is to check the sizes:
if (values.size() != otherStack.values.size()) {
return false;
}
// Finally, go through the individual elements in a loop
In the loop that follows, do not pop the other stack. Do not do anything that can modify it. Simply go through the underlying storage (i.e. values), and check elements one by one.
Don't forget to override hashCode as well: you need to do it every time when you override equals for the object to fulfill the contract specified by java.lang.Object.

Returning a value to caller via chain of methods

Say I call a method. I want a return value from that method. However, this method delegates tasks to other methods, which in turn may delegate tasks to other methods still. The value that gets eventually returned by the top most method is ultimately determined by the submethods, and the submethods' submethods.
Imagine this scenario:
public String method1(Object o){
if(x)
return subMethod1(o);
if(y)
return subMethod2(o);
if(z)
return subMethod3(o);
else
return "";
}
//example submethod
public String subMethod1(Object o){
if(a)
return subSubMethod1(o);
if(b)
return subSubMethod2(o);
if(c)
return subSubMethod3(o);
else
return "";
}
//example subsubmethod
public String subSubMethod1(Object o){
//etc etc
return "";
}
This a reoccurring problem for me, and I am hoping there is a design pattern to solve this type of problem.
Is there such a design pattern?
If you really want to go with a design pattern, Chain of Responsibility is the closest pattern I can think of for your situation. But this can go overboard very quickly
public interface Handler{
void setNext(Handler h);
String handle(Object o);
}
public class Method1Handler implements Handler{
private Handler next;
#Override
public void setNext(Handler h){
this.next= h;
}
#Override
public String handle(Object o){
if(x){
return subMethod1();
}else if(next !=null){
return next.handle(o);
}
return "";
}
}
Of course subMethod1() would also use CoR etc. It could get pretty ugly but the top level is clean:
//top level of code
Method1Handler handler = new Method1Handler();
//...lots of set next
//...and set next of nexts etc
//...
return myHandler.handle(o);
The conditional operator makes each set of choices simple - and if you lay it out correctly, it's really easy to read, once you've got the hang of the pattern:
return x ? subMethod1(o)
: y ? subMethod2(o)
: z ? subMethod3(o)
: "";
Of course, if your decisions could actually be laid out along polymorphic lines (i.e. the conditions map to which type the object is at execution time) then you can use inheritance to solve this instead. But if you really do just need multiple conditions like this, the conditional operator can be very helpful.

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

Search an attribute inside a Vector on Java

I've a Vector of objects, and have to search inside for a random attribute of those objects (For example, a Plane class, a Vector containing Plane; and I've to search sometimes for destination, and others to pilotName).
I know I can traverse the Vector using an Iterator, but I've got stuck at how do I change the comparison made between a String and the attribute on the object. I thought of using switch, but a another opinion would be cool.
Update 1:
The code I've written is something like this (Java n00b alert!):
public int search(String whatSearch, String query){
int place = -1;
boolean found = false;
for ( Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false; ) {
Plane temp = (Plane) iteraPlane.next();
/* Here is where I have to search for one of many attributes (delimited by whatSearch */
}
return place;
}
Seems I've to stick to linear search (and that's a price I've able to pay). Anyway, I was thinking if Java had something like variable variable name (ouch!)
I assume that your problem is that you want to have a method that searches for a result based on some property of the collection type. Java is weak on this because it is best expressed in a language which has closures. What you need is something like:
public interface Predicate<T> {
public boolean evaluate(T t);
}
And then your search method looks like:
public static <T> T findFirst(List<T> l, Predicate<T> p) { //use List, not Vector
for (T t : l) { if (p.evaluate(t)) return t; }
return null;
}
Then anyone can use this general-purpose search method. For example, to search for an number in a vector of Integers:
List<Integer> is = ...
findFirst(is, new Predicate<Integer> {
public boolean evaluate(Integer i) { return i % 2 == 0; }
});
But you could implement the predicate in any way you want; for any arbitrary search
Use Collections.binarySearch and provide a Comparator.
EDIT: This assumes that the Vector is sorted. Otherwise, one has to do a linear search.
the equals() method is the best option. For these iterations you could do something like this:
for (Plane plane: planes) {
if ("JFK".equals(plane.getDestination())) {
// do your work in here;
}
}
or you could override the equals() method within Plane to see if the String passed in matches your destination (or pilot). this will allow you to use the indexOf(Object) and indexOf(Object, index) methods on Vector to return you the index(es) of the object(s). Once you have that, you could use Vector.get(index) to return to Object for you.
in Plane.java:
public boolean equals(Object o) {
return o.equals(getDestination()) ||
o.equals(getPilot()) ||
super.equals(o);
}
there is more work to be done with this option, as you will need to override hashCode() as well (see documentation).
See #oxbow_lakes above -- I think what you want isn't to pass a String as whatSearch, it's to pass a little snippet of code that knows how to get the property you're interested in. For a less general version:
public static interface PlaneMatcher {
boolean matches(Plane plane, String query);
}
public int search(PlaneMatcher matcher, String query){
int place = -1;
boolean found = false;
for ( Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false; ) {
Plane temp = (Plane) iteraPlane.next();
if (matcher.matches(temp, query) {
found = true;
}
place++;
}
return place;
}
...
// example
int pilotNameIndex = search(new PlaneMatcher() {
boolean matches(Plane plane, String query) {
// note: assumes query non-null; you probably want to check that earlier
return query.equals(plane.getPilotName());
}
}, "Orville Wright");
(By the way, if it's the index you're interested in rather than the Plane itself, I wouldn't bother with an Iterator -- just use an old-fashioned for (int i = 0; i < planes.size(); i++) loop, and when you have a match, return i.)
Now, the tricky bit here is if what you have to search for is really identified by arbitrary strings at run-time. If that's the case, I can suggest two alternatives:
Don't store these values as object fields -- plane.pilotName, plane.destination -- at all. Just have a Map<String, String> (or better yet, a Map<Field, String> where Field is an Enum of all the valid fields) called something like plane.metadata.
Store them as object fields, but prepopulate a map from the field names to PlaneMatcher instances as described above.
For instance:
private static final Map<String, PlaneMatcher> MATCHERS = Collections.unmodifiableMap(new HashMap<String, PlaneMatcher>() {{
put("pilotName", new PlaneMatcher() {
boolean matches(Plane plane, String query) {
return query.equals(plane.getPilotName());
});
...
put("destination", new PlaneMatcher() {
boolean matches(Plane plane, String query) {
return query.equals(plane.getDestination());
});
}}
...
public int search(String whatSearch, String query){
PlaneMatcher matcher = MATCHERS.get(whatSearch);
int place = -1;
boolean found = false;
for ( Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false; ) {
Plane temp = (Plane) iteraPlane.next();
if (matcher.matches(temp, query) {
found = true;
}
place++;
}
return place;
}
Oh, and you might be tempted to use reflection. Don't. :)
A simple way is to pass a comparison function to your search routine. Or, if you need more speed, use generics.

Categories