So my class takes data and does it's thing, returning an error message if anything went wron开发者_JAVA技巧g. What should I make the string if everything went fine? null? "1"? "OK!"? "success"?
Please support your answer.
Unix standard return codes use '0' as OK - by analogy, it's often recommended to use empty string (length 0), at least in languages where you can treat the "" value as "false".
E.g., in Perl: if ( $error = my_method_call() ) { print "Failed: $error\n" }
In a language where there's no such implication (use "" as false), any string can be chosen as "OK", as long as it's obvious and readable ("OK" fits the bill).
Methods should never return string errors. They are way too error prone and are more costly than the obvious alternative, returning integer codes, which you can translate to descriptive constants and have a single method which translates those codes to strings.
If you will use error codes to print them out (or log them), then it might be fine to use strings, but then again, there is nothing preventing you from printing or logging the error in the erroring method itself and returning a failing status code to the caller.
If you will use string error codes to check internally in code for different conditions, strings are a pain:
rv = some_function();
if (rv == "The file could not be read") {
take_corrective_action();
}
About including details in error code, the caller (usually) has the details and can compose the complete error message:
rv = read_data(FILE);
if (rv == READ_PERMISSION_ERROR) {
log("The file " + FILE + " could not be read. You don't have permissions");
}
精彩评论