Return Codes in OOP
I've recently worked on a project where every method contained a return code. Example:
public Boolean LoadPageData(out int returnCode) { ... }
or
public String GetCustomerName(out int returnCode) { ... }
Is using return codes considered good practice, bad practice, or simply personal preference in the context of OOP programing (Specifically ASP.Net)? If the开发者_StackOverflow中文版y do have a place is including a return code on every method the correct usage?
Typically, the need for return codes in addition to the regular return value is a sign of poor design.
Return codes are used to signal success or various degrees of failure. In OOP, a method succeeds if the method returns at all. If there are any various degrees of failure, you should throw the appropriate exception.
The preferred way to signal errors in OOP is to throw exceptions. Return codes are common in C where there are no exceptions. Make your own exceptions if you wish that take certain custom parameters, or make an enum of exception types and pass those to a generic exception class. There is a lot of flexibility here, don't get too complicated, just do what works for now.
You should use exceptions to indicate an error has occured rather than return codes. See here for more. Return codes were used before exceptions.
I think that in languages with exceptions and exception handling, the preferred way to handle exceptional scenarios is to use that framework. If you're not talking about exceptional scenarios, I'd still share your hesitation to assume that return codes are a great idea... you could encapsulate just about any semantic information associated with return codes in the class itself, I think.
It is not good practice. Exceptions are the preferred way of handling exceptional cases. Requiring the caller to specify an out parameter with every method call is also unecessarily cumbersome.
Use XML comments to warn the caller of thrown or possible unhandled exceptions.
精彩评论