I´ve lately been thinking about the things i´m returning from methods and I noticed that there are 4 different things i return when the method fails.
What bothers me about it, is that my code is not very consitent in this regard, so i wanted to ask about your "best practices".
So lets imagine a method that takes Foo and returns a list of Bar:
public IList<Bar> Method(Foo something);
Or to keep it more general:
public IBar Method(IFoo something);
The question is what do you return on what kind of failure. the options would be:
I really hate option 4 so I´m mostly interessted to hear when you use the other 3 options and why
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough. When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code.
Does throwing an exception within a method cause the method to return? Yes. Execution of a method is being interrupted, so method returns it execution flow.
You do not need to put a return statement after throw , the return line will never be reached as throwing an exception immediately hands control back to the caller.
For example Note that throwing an exception means that the method was used wrong or had an internal error, while returning an exception means that the error code was identified successfully.
I'd choose between an empty list and an exception depending on the nature of the failure.
E.g.
If your database failed to connect - exception.
If your query didn't return results - empty list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With