Question

How can i replace assertions with if's? Example:

public Wezel<Wartosc,Indeks> getWujek() 
    {
        assert rodzic != null; // Root node has no uncle
        assert rodzic.rodzic != null; // Children of root has no uncle
        return rodzic.getBrat();
    }
Was it helpful?

Solution

An assertion is roughly equivalent to:

if (!condition) {
    throw new AssertionError();
}

OTHER TIPS

public Wezel<Wartosc,Indeks> getWujek() 
    {
        if(rodzic == null) { // Root node has no uncle
            throw new Exception("Root node has no uncle");
        }
        if(rodzic.rodzic == null) {
            throw new Exception("Children of root have no uncle");
        }
        return rodzic.getBrat();
    }

Replacing these assertions would take the form of the following validation:

if (rodzic == null)
   throw new MyValidationException("rodzic cannot be null");
if (rodzic.rodzic == null)
   throw new MyValidationException("rodzic.rodzic cannot be null");
return rodzic.getBrat();

Note that there's a distinction between throwing an Exception and an Error - Exceptions are meant to be caught and handled farther up, while Errors indicate a situation that you can't recover from. For example, you might consider a defining and using a MyValidationError if the failed check is irrecoverable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top