Search code examples
javaalgorithminfinite-loop

check parent-child loop function


I'm trying to create a function that can recognize the parent-child loop.
Imagin

Object A is a parent of Object B
Object B is a parent of Object C

create a function that can prevent the parent-child loop. the function should give at least two parameters (childName, parentName) and get errors if the relationship creates a loop. in the above example if we pass (A, C) should print or pass string:

"A is the parent of C"

I know how to create this function(you can provide answer with any language):

private static void restrict_ParentChild_Loop(Object A, Object B) throws Exception {
    if (A.parent == null)
        return;
    if (A.parent.equals(B)) {
        throw new Exception("");
    } else {
        restrict_ParentChild_Loop(A.parent, B);
    }
}

My main question is about how to provide the right message in the Exception. ("A is the parent of C")


Solution

  • My main question is about how to provide right message in the Exception.

    I'm still wondering why that's not the question title itself.

    Since this question is likely opinion-based... I'll give my shot?

    Your code at:

    throw new Exception("");
    

    Will throw an Exception like this:

    java.lang.Exception: At ...
    

    So it will be even better if you just tell it what you want it to show in the first place:

    throw new Exception(A.parent+" is the parent of "+B.child);
    //This throws:
    java.lang.Exception: A is the parent of C: At ...
    

    Which results in:

    private static void restrict_ParentChild_Loop(Object A, Object B) throws Exception {
        if (A.parent == null)
            return;
        if (A.parent.equals(B)) {
            throw new Exception(A.parent+" is the parent of "+B.child);
        } else {
            restrict_ParentChild_Loop(A.parent, B);
        }
    }