Say I have a method that inserts a record into the database. I don't need to know the newly-inserted ID or anything else. I have two options:public void Insert()public string Insert()In the first: if an insert is successful, the calling code will continue. If it fails, an exception with the details will be returned and the calling code will handle it in the catch.In the second: the calling code will interrogate the return string for specific words to see whether or not it was successful.Which option is better and why?
What is the downside of returning a string instead of a void function or throwing an exception?
.net
IMO the void method is preferred. In OO programming it is better style to simply use objects and if there is an error throw an exception which can be caught. The exception thrown should be pertinent to the error and descriptive - the descriptive message may not be shown to the user but logged, depending on the scenario. This is also the most common approach of the developers I have encountered using .Net.The problem with returning a string is that soon your code will be cluttered with similarly crafted methods, causing conditional statements to proliferate in the codebase. Ultimately this becomes a maintenance problem as it reduces readability. It is error prone as developers may forget to check for certain failures. It provides less information to the caller if there was an error, unlike an exception, unless you filled the string with all sorts of information which would then need to be parsed. It requires silently handling exceptions in methods then returning some failure message, a rather strange approach to say the least!In fact the more I think about it the more horrifying it seems. Follow the KISS philosophy - keep it simple and stupid! Don't pollute your code base with all of these decision points.Don't go the other way though and put try/catch everywhere you think an exception will occur either. Let exceptions bubble up the call stack and handle at appropriate junctures according to the specifics of the application. Clean code will be more achievable then.