[Solved] Which is the Best way to exit a method


There is no best way, it depends on situation.

Ideally, there is no need to exit at all, it will just return.

int a() {
    return 2;
}

If there is a real need to exit, use return, there are no penalties for doing so.

void insertElementIntoStructure(Element e, Structure s) {
    if (s.contains(e)) {
        return; // redundant work;
    }
    insert(s, e); // insert the element
}

this is best avoided as much as possible as this is impossible to test for failure in voids

Avoid system.exit in functions, it is a major side effect that should be left to be used only in main.

void not_a_nice_function() {
    if (errorDetected()) {
        System.exit(-1);
    }
    print("hello, world!");
}

this pseudocode is evil because if you try to reuse this code, it will be hard to find what made it exit prematurely.

3

solved Which is the Best way to exit a method