You’re designing a method. It serves a purpose, that’s why you’re designing it in the first place. A caller uses your method and the method fails, but, lo and behold, the ultimate purpose that exuse the existence of the method is nevertheless achieved — thanks to external circumstances that are out of your control or some kind of magic, you choose. Would you report this situation to the caller as a failure or as a success?
Let’s pick a trivial example. You’re writing a DeleteFile function. It takes a file path and deletes the file. Someone calls this function, providing a path. The function looks the file up, but it does not exist. It’s not a permissions issue or something, the file is genuinely missing. Maybe another process deleted it a microsecond ago, and maybe it never existed at all. The function failed to perform its task, so it must report a failure… but the only reason why a user whould call this function is to make sure a file does not exist, and, voila, it does not, so it is a success.
I anticipate answers like “just be more verbose in your return values”, and I’m happy to return a verbose result as a complimentary information, but what (and why) would you return as a primary success flag of the function, success or failure? Would it be FALSE with additional flag of BUT_DOES_NOT_EXIST_ANYWAY, or would it be TRUE with a BUT_THANK_SOMEONE_ELSE flag?
I’m asking about situation in general, including when the method has no parameters or it is not possible to call it in a wrong way for some other reason.
When new programmers are learning how to write functions, the terms preconditions and postconditions are often introduced. Preconditions are assumptions that must be met for your method to work properly. Postconditions are guarantees that your method makes about the state of the system after execution.
I think that a reasonable precondition to expect when calling a
deleteFilemethod is that the file currently exists. If the preconditions are not met, the method should fail, even if the postconditions have been achieved in an accidental, roundabout way.Now, if your method were called
deleteFileIfExists, that’s a different story. You haven’t imposed such strict preconditions on the method.