I'm doing some networking stuff in one of my methods and I would like the method to return NO
and stop executing early if one of the internal calls returns an error, a bit like break for loops. Is this possible?
IMO it would produce cleaner code rather than using a BOOL flag and having "should I continue executing this code?" if statements all over the place; and then finally at the end of the method returning YES or NO开发者_开发知识库 based on the flag.
Any thoughts are much appreciated!
Yes, you can.
return NO;
Return statements are acceptable everywhere in functions and methods. I personally prefer to make use of early returns because it usually leads to less nesting (and thus code easier to understand).
There are several similar questions around here:
- Should I use early returns in C#?
- Is it bad to have multiple return statements?
- Should a function have only one return statement?
精彩评论