I'm trying to call a web service that saves user information. Essentially, a 'completion' object is returned with the results of the service call. The code I have can be condensed as follows:
public bool SaveUserInformation(ArgsList args) {
CompletionObject results = SaveService(args);
if (results.Status == Failed)
throw SomeException("onoez D:");
return true;
}
Essentially, this method returns a boolean but the 开发者_JAVA技巧value is never false. This seems a little strange to me, so is there a better way to approach this?
Thanks!
Why not return void
? If an exception is thrown then you will know it. If it isn't thrown, you know that your function completed successfully (returned true).
try
{
MyFunction();
//here you know it has successfully completed
}
catch(Exception e)
{
//...
}
If, however, you're overriding a virtual function which returns bool then you can of course always return true, since you have to return some boolean value anyway. Come to think of it, you can return false as well :)
Exception
is for exceptional cases.
Return value
is for indicating caller about something happened inside called function.
They are completely different design concepts.
Deside what you want the behaviour of that method looks like.
If there is nothing to notify about, remove return value.
If there is, check if there is really sense to have all that exceptions handling.
Based on this question and after looking at your code, I would say YES.
This function returns true regardless of the outcome, so its return value has no meaning.
Now, on the other hand, if you had tried to open a file that did not exist, you would also get an Exception. If you handled that Exception and used a default file or loaded default values and everything still worked out... then returning true would be logical.
The function you have shown is not helpful to anyone using it ...unless you have left something out of it.
Why even make it return a boolean? You either return the error as a true/false value or you just return nothing and rely on exceptions.
Why not simply return CompletionObject
public CompletionObject SaveUserInformation(ArgsList args) {
return SaveService(args);
/*if (results.Status == Failed)
throw SomeException("onoez D:");
return true;*/
}
I am not able to understand the need for a bool return value as its always true.
精彩评论