Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long try statements

Is there any drawback to putting most of your code for your function in a try statement. If I do something that requires a try statement, I usually end up doing a lot of work for that function inside the try statement because I usually declare my variables in there and can't use them outside that scope if I do that. Is this common and accepted? Do people usually declare variable before without initializing them so they're not doing everything (including calls to other functions) inside a try statement? Or does it not matter if it's very long?

like image 840
user1136342 Avatar asked Dec 15 '22 14:12

user1136342


1 Answers

A method should do one thing and do it good. In this case your method is doing two things: business logic and error handling:

public Foo bar() {
    try {
        //business logic that may throw
        //...
        //end even more
    } catch(BuzzException e) {
        //Error handling
    }
}

Very often I find myself extracting the contents of try block into a separate method without error handling:

public Foo bar() {
    try {
        return unsafeBar();
    } catch(BuzzException e) {
        //Error handling
    }
}

public Foo unsafeBar() throws BuzzException {
    //business logic that may throw
    //...
    //end even more
}
like image 63
Tomasz Nurkiewicz Avatar answered Jan 06 '23 02:01

Tomasz Nurkiewicz