Should a connect method return a value? - c#

I was looking at some code I've inherited and I couldn't decided if I like a bit of code.
Basically, there is a method that looks like the following:
bool Connect(connection parameters){...}
It returns true if it connects successfully, false otherwise.
I've written code like that in the past, but now, when I see this method I don't like it for a number of reasons.
Its easy to write code that just ignores the returned value, or not realize it returns a value.
There is no way to return an error message.
Checking the return of the method doesn't really look nice:
if (!Connect(...)){....}
I could rewrite code to throw an exception when it doesn't successfully connect, but I don't consider that an exceptional situation. Instead I'm thinking of refactoring the code as follows:
void Connect(Connection Parameters, out bool successful, out string errorMessage){...}
I like that other developers have to provide the success and error strings so they know the method has error conditions and I can know return a message
Anyone have any thoughts on the matter?
Thanks
-Matt

I would opt for the exception versus the out parameters. If you want consumers of your class to care, make them care with the Exception, or else leave them alone. By using the out parameters, you're simply making their lives more inconvenient if they don't have to care by making them use throwaway variables. Also consider that if your function is already in the wild, you're introducing a breaking change if you change the signature (instead of providing an additional overload).
Programmers expect exceptions in error cases, particularly in languages like C#. We've been trained.

I have only an opinion, so take it for what its worth.
A method named like this, "Connect", is an order. It's like giving it to a soldier, "Jump" or "Shoot". You don't expect the soldier to report back unless he's unable to complete the order, and that would be a rare happening.
As such, I have the tendency to not have a return value for such methods, but if there is a chance that under regular usage of the method, there will be failures, then I build a second method, named TryXYZ, returning a bool, and if necessary providing me with the results of whatever XYZ is as out parameters.
This follows the standard set forth by the Parse methods of various numeric types in the .NET BCL.
So in your case, I would probably have:
void Connect(connection parameters);
bool TryConnect(connection parameters, out status);
The nice thing is that if you build the TryConnect method properly, Connect becomes really easy.
Example:
public bool TryConnect(string connectionString, out ConnectionStatus status)
{
... try to connect
... set status, and return true/false
}
public void Connect(string connectionString)
{
ConnectionStatus status;
if (!TryConnect(connectionString, out status))
switch (status)
{
case ConnectionStatus.HostNotFound:
throw new HostNameNotFoundException();
...
}
}
I don't expect my orders to not complete, but in the sense they might, I want to be explicit about it.

I see your points but to add my 2c.
I generally am not a fan of output parameters. If you need to return multiple values from a function re-evaluate what the function is doing, in most case multiple return values is a sign that a method does too much. In your case it is legitimate a complex type would be returned from your connect method (beyond a simple boolean).
I would be in favor of returning a custom type from the connect method that stores all relevant information rather than multiple output parameters. Think about future extensibility, what if you need to include more information down the road. Adding additional output parameters is a breaking change
Also, I tend to disagree with forcing a user to provide memory allocations for all state data. There can be times when I don't care about the success message (maybe I only care if it errors) in which case having to pass both output params is a pain.
I do agree though that checking the return value of the initial method posted isn't ideal.

I don't mind the Connect function returning a boolean and I'm not a big fan of output parameters. If the function did not return the connection state you'd probably have to write a IsConnected function/property (depending on your style) anyway to allow someone to check it, so it saves a step.
As far as expections go, let the exception be caught by the calling code, that'll force the caller to care. :)

I agree that failing to establish a connection (in most cases) should not be seen as an exceptional situation. However to force the user to provide arguments for error string etc. isn't nice either. Other possible solutions:
Use logging. Drawback is that messages are written to the log but not (without much effort) available to the caller.
Use boolean return and provide methods for querying the last error (like errno in C). IMHO not nice either.
Refactor your code, return an object of a connection class. Provide methods to query connection state.
return an instance of a class that gathers all relevant information, aka isSuccessfull(), getErrorString, etc.

Not sure if this is any better than your refactoring code, but hopefully this could give you another idea.
For my projects, I create a method that returns the last error message.
string Error = '';
bool Connect(connection parameters)
{
// do my connection here
// if there's an error set string variable Error
// This way you can set different error message depending on what you're doing
}
string lastErrorMessage(){
// return Error string
}
This way you can do this:
if(!connect(...))
{
string message = lastErrorMessage();
// Then do what you need here.
}
This might not be the best way, but should help you :)

Related

How to invoke methods from Controller when some of them are void and some are not?

I am a student and I am currently preparing for my OOP Basics Exam.
When in the controller you have methods which return a value and such that are void - how do you invoke them without using a if-else statement?
In my code "status" is the only one which should return a string to be printed on the Console - the others are void. So I put a if-esle and 2 methods in the CommandHandler.
Since I know "if-else" is a code smell, is there a more High Quality approach to deal with the situation?
if (commandName == "status")
{
this.Writer.WriteLine(this.CommandHandler.ExecuteStatusCommand(commandName));
}
else
{
this.CommandHandler.ExecuteCommand(commandName, commandParameters);
}
This is the project.
Thank you very much.
First, don't worry about if/else. If anybody tells you if/else is a code smell, put it through the Translator: What comes out is he's telling you he's too crazy, clueless, and/or fanatical to be taken seriously.
If by ill chance you get an instructor who requires you to say the Earth is flat to get an A, sure, tell him the Earth is flat. But if you're planning on a career or even a hobby as a navigator, don't ever forget that it's actually round.
So. It sounds to me like CommandHandler.ExecuteStatusCommand() executes the named command, which is implemented as a method somewhere. If the command method is void, ExecuteStatusCommand() returns null. Otherwise, the command method may return a string, in which case you want to write it to what looks like a stream.
OK, so one approach here is to say "A command is implemented via a method that takes a parameter and returns either null or a string representing a status. If it returns anything but null, write that to the stream".
This is standard stuff: You're defining a "contract". It's not at all inappropriate for command methods which actually return nothing to have a String return type, because they're fulfilling the terms of contract. "Return a string" is an option that's open to all commands; some take advantage, some don't.
This allows knowledge of the command's internals to be limited to the command method itself, which is a huge advantage. You don't need to worry about special cases at the point where you call the methods. The code below doesn't need to know which commands return a status and which don't. The commands themselves are given a means to communicate that information back to the caller, so only they need to know. It's incredibly beneficial to have a design which allows different parts of your code not to care about the details of other parts. Clean "interfaces" like this make that possible. The calling code gets simpler and stays simpler. Less code, with less need to change it over time, means less effort and fewer bugs.
As you noted, if you've got a "status" command that prints a result, and then later on you add a "print" command that also prints a result, you've got to not only implement the print command itself, but you've also got to remember to return to this part of your code and add a special case branch to the if/else.
That kind of tedious error-prone PITA is exactly the kind of nonsense OOP is meant to eliminate. If a new feature can be added without making a single edit to existing code, that's a sort of Platonic ideal of OOP.
So if ExecuteCommand() returns void, we'll want to be calling ExecuteStatusCommand() instead. I'm guessing at some things here. It would have been helpful if you had sketched out the semantics of those two methods.
var result = this.CommandHandler.ExecuteCommand(commandName, commandParameters);
if (result != null)
{
this.Writer.WriteLine(result);
}
If my assumptions about your design are accurate, that's the whole deal. commandParameters, like the status result, are an optional part of the contract. There's nothing inherently wrong with if/else, but sometimes you don't need one.

Testing methods with overloading using shims and stubs in VS 2013 c# Code [duplicate]

What is the best way to unit test a method that doesn't return anything? Specifically in c#.
What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.
If a method doesn't return anything, it's either one of the following
imperative - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
informational - just notifying someone that something happened (without expecting action or response) respectively.
Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.
void DeductFromBalance( dAmount )
can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount
Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.
void OnAccountDebit( dAmount ) // emails account holder with info
can be tested by verifying if the email is being sent
Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.
string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );
String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like
InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );
Test its side-effects. This includes:
Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)
Does it have the right effect on the state of the object/type you're calling it on?
Of course, there's a limit to how much you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.
As always: test what the method is supposed to do!
Should it change global state (uuh, code smell!) somewhere?
Should it call into an interface?
Should it throw an exception when called with the wrong parameters?
Should it throw no exception when called with the right parameters?
Should it ...?
Try this:
[TestMethod]
public void TestSomething()
{
try
{
YourMethodCall();
Assert.IsTrue(true);
}
catch {
Assert.IsTrue(false);
}
}
Void return types / Subroutines are old news. I haven't made a Void return type (Unless I was being extremely lazy) in like 8 years (From the time of this answer, so just a bit before this question was asked).
Instead of a method like:
public void SendEmailToCustomer()
Make a method that follows Microsoft's int.TryParse() paradigm:
public bool TrySendEmailToCustomer()
Maybe there isn't any information your method needs to return for usage in the long-run, but returning the state of the method after it performs its job is a huge use to the caller.
Also, bool isn't the only state type. There are a number of times when a previously-made Subroutine could actually return three or more different states (Good, Normal, Bad, etc). In those cases, you'd just use
public StateEnum TrySendEmailToCustomer()
However, while the Try-Paradigm somewhat answers this question on how to test a void return, there are other considerations too. For example, during/after a "TDD" cycle, you would be "Refactoring" and notice you are doing two things with your method... thus breaking the "Single Responsibility Principle." So that should be taken care of first. Second, you might have idenetified a dependency... you're touching "Persistent" Data.
If you are doing the data access stuff in the method-in-question, you need to refactor into an n-tier'd or n-layer'd architecture. But we can assume that when you say "The strings are then inserted into a database", you actually mean you're calling a business logic layer or something. Ya, we'll assume that.
When your object is instantiated, you now understand that your object has dependencies. This is when you need to decide if you are going to do Dependency Injection on the Object, or on the Method. That means your Constructor or the method-in-question needs a new Parameter:
public <Constructor/MethodName> (IBusinessDataEtc otherLayerOrTierObject, string[] stuffToInsert)
Now that you can accept an interface of your business/data tier object, you can mock it out during Unit Tests and have no dependencies or fear of "Accidental" integration testing.
So in your live code, you pass in a REAL IBusinessDataEtc object. But in your Unit Testing, you pass in a MOCK IBusinessDataEtc object. In that Mock, you can include Non-Interface Properties like int XMethodWasCalledCount or something whose state(s) are updated when the interface methods are called.
So your Unit Test will go through your Method(s)-In-Question, perform whatever logic they have, and call one or two, or a selected set of methods in your IBusinessDataEtc object. When you do your Assertions at the end of your Unit Test you have a couple of things to test now.
The State of the "Subroutine" which is now a Try-Paradigm method.
The State of your Mock IBusinessDataEtc object.
For more information on Dependency Injection ideas on the Construction-level... as they pertain to Unit Testing... look into Builder design patterns. It adds one more interface and class for each current interface/class you have, but they are very tiny and provide HUGE functionality increases for better Unit-Testing.
You can even try it this way:
[TestMethod]
public void ReadFiles()
{
try
{
Read();
return; // indicates success
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
it will have some effect on an object.... query for the result of the effect. If it has no visible effect its not worth unit testing!
Presumably the method does something, and doesn't simply return?
Assuming this is the case, then:
If it modifies the state of it's owner object, then you should test that the state changed correctly.
If it takes in some object as a parameter and modifies that object, then your should test the object is correctly modified.
If it throws exceptions is certain cases, test that those exceptions are correctly thrown.
If its behaviour varies based on the state of its own object, or some other object, preset the state and test the method has the correct Ithrough one of the three test methods above).
If youy let us know what the method does, I could be more specific.
Use Rhino Mocks to set what calls, actions and exceptions might be expected. Assuming you can mock or stub out parts of your method. Hard to know without knowing some specifics here about the method, or even context.
Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.
What ever instance you are using to call the void method , You can just use ,Verfiy
For Example:
In My case its _Log is the instance and LogMessage is the method to be tested:
try
{
this._log.Verify(x => x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure");
}
Catch
{
Assert.IsFalse(ex is Moq.MockException);
}
Is the Verify throws an exception due to failure of the method the test would Fail ?

Methods that return meaningful return values

I work in C#, so I've posted this under C# although this may be a question that can be answered in any programming language.
Sometimes I will create a method that will do something such as log a user into a website. Often times I return a boolean from the method, but this often causes problems because a boolean return value doesn't convey any context. If an error occurs whilst logging the user in I have no way of knowing what caused the error.
Here is an example of a method that I currently use, but would like to change so that it returns more than just 0 or 1.
public bool LoginToTwitter(String username, String password)
{
// Some code to log the user in
}
The above method can only return True or False. This works well because I can just call the following:
if(http.LoginToTwitter(username, password))
{
// Logged in
} else {
// Not Logged in
}
But the problem is I have no way of knowing why the user wasn't logged in. A number of reasons could exist such as: wrong username/password combination, suspended account, account requires users attention etc. But using the following method, and logic, it isn't possible to know this.
What alternative approaches do I have?
You could create and return an enum with expected LoginResults.
public enum LoginResult
{
Success,
AccountSuspended,
WrongUsername,
WrongPassword,
}
Then return using the enum type in your method:
public LoginResult LoginToTwitter(String username, String password)
{
// Some code to log the user in
}
You could choose to either throw an exception with a relevant message attached (and have the calling method deal with the exception), or have the function return an enum with different states (such as LoginState.Success, LoginState.IncorrectPassword, etc.).
If you are using exceptions, it's probably best to have your function return nothing (public void LoginToTwitter), but if you're using an enum, make sure the set the return type to the name of your enum (public LoginState LoginToTwitter).
There are two standard ways. If you're interested in just the outcome, but not any metadata, return some enum instead. Set the available values to Success, Suspended, etc. (all your possible outcomes)
If you need some more details, you can always use exceptions. Basically follow the "tell, don't ask" idea and write your function in a way that it returns required values (user id for example? or maybe nothing if you have some global login state) only on success and throws an exception with detailed description of the failure otherwise. Regarding the hierarchy itself, you should most likely implement a LoginException with some more specific subclasses and catch only those. (it makes it easy to verify all relevant exceptions are handled and all unknown ones are passed to higher levels)
Both returning an enum or throwing an exception, as suggested in other answers, are reasonable. But my preference is to return an exception. Sounds crazy, but it lets your caller decide whether to use error checking or exception handling. And, unlike the enum, exceptions are hierarchical, so it makes it much easier to handle entire categories of failures, and can carry arbitrary extra data.
I think Sayse had a similar idea, but he deleted his answer and never really explained it either.
According to clean code tendency you should provide a meaningfull name for your method that reveal intent.
For to know what happened if logging operation could no be completed you can introduce in your flow Exceptions and handle it in the caller context.
see http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx
You can use an idiom that is frequently used in c. The result of an assignment expression is the expression itself - this means you can capture a result code at the same time as evaluating whether it's a particular value:
if ((status = DoSomething()) == AnErrorEnum.NotAnError)
{//success handler
}
else
{//failure handler
}
I was asked to provide a link to an MSDN article - here is an old version of the spec:
http://msdn.microsoft.com/en-us/library/aa691315(v=vs.71).aspx
"The result of a simple assignment expression is the value assigned to the left operand. The result has the same type as the left operand and is always classified as a value."

Is this good C# style?

Consider the following method signature:
public static bool TryGetPolls(out List<Poll> polls, out string errorMessage)
This method performs the following:
accesses the database to generate a list of Poll objects.
returns true if it was success and errorMessage will be an empty string
returns false if it was not successful and errorMessage will contain an exception message.
Is this good style?
Update:
Lets say i do use the following method signature:
public static List<Poll> GetPolls()
and in that method, it doesn't catch any exceptions (so i depend the caller to catch exceptions). How do i dispose and close all the objects that is in the scope of that method? As soon as an exception is thrown, the code that closes and disposes objects in the method is no longer reachable.
That method is trying to do three different things:
Retrieve and return a list of polls
Return a boolean value indicating success
Return an error message
That's pretty messy from a design standpoint.
A better approach would be to declare simply:
public static List<Poll> GetPolls()
Then let this method throw an Exception if anything goes wrong.
This is definitely not an idiomatic way of writing C#, which would also mean that it probably isn't a good style either.
When you have a TryGetPolls method then it means you want the results if the operation succeeds, and if it doesn't then you don't care why it doesn't succeed.
When you have simply a GetPolls method then it means you always want the results, and if it doesn't succeed then you want to know why in the form of an Exception.
Mixing the two is somewhere in between, which will be unusual for most people. So I would say either don't return the error message, or throw an Exception on failure, but don't use this odd hybrid approach.
So your method signatures should probably be either:
IList<Poll> GetPolls();
or
bool TryGetPolls(out IList<Poll> polls);
(Note that I'm returning an IList<Poll> rather than a List<Poll> in either case too, as it's also good practice to program to an abstraction rather than an implementation.)
I believe
public static bool TryGetPolls(out List<Poll> polls)
would be more appropriate. If the method is a TryGet then my initial assumption would be there is reason to expect it to fail, and onus is on the caller to determine what to do next. If they caller is not handling the error, or wants error information, I would expect them to call a corresponding Get method.
As a general rule, I would say no.
The reason I say no is actually not because you're performing a TryGetX and returning a bool with an out parameter. I think it's bad style because you're also returning an error string.
The Try should only ignore one specific, commonly-encountered error. Other problems may still throw an exception with the appropriate exception message. Remember that the goal of a Try method like this is to avoid the overhead of a thrown exception when you expect a particular, single sort of failure to happen more frequently than not.
Instead, what you're looking for is a pair of methods:
public static bool TryGetPolls( out List<Poll> polls );
public static List<Poll> GetPolls();
This way the user can do what's appropriate and GetPolls can be implemented in terms of TryGetPolls. I'm assuming that your staticness makes sense in context.
Consider returning:
an empty collection
null
Multiple out parameters, to me, is a code smell. The method should do ONE THING only.
Consider raising and handling error messages with:
throw new Exception("Something bad happened");
//OR
throw new SomethingBadHappenedException();
No, from my point of view this is very bad style. I would write it like this:
public static List<Poll> GetPolls();
If the call fails, throw an exception and put the error message in the exception. That's what exceptions are for and your code will become much cleaner, more readable and easier to maintain.
Not really - I can see a number of problems with this.
First of all, the method sounds like you'd normally expect it to succeed; errors (cannot connect to database, cannot access the polls table etc) would be rare. In this case, it is much more reasonable to use exceptions to report errors. The Try... pattern is for cases where you often expect the call to "fail" - e.g. when parsing a string to an integer, chances are good that the string is user input that may be invalid, so you need to have a fast way to handle this - hence TryParse. This isn't the case here.
Second, you report errors as a bool value indicating presence or absence of error, and a string message. How would the caller distinguish between various errors then? He certainly can't match on error message text - that is an implementation detail that is subject to change, and can be localized. And there might be a world of difference between something like "Cannot connect to database" (maybe just open the database connection settings dialog in this case and let the user edit it?) and "Connected to database, but it says 'Access Denied'". Your API gives no good way to distinguish between those.
To sum it up: use exceptions rather than bool + out string to report messages. Once you do it, you can just use List<Poll> as a return value, with no need for out argument. And, of course, rename the method to GetPolls, since Try... is reserved for bool+out pattern.
The guidelines say to try to avoid ref and out parameters if they are not absolutely required, because they make the API harder to use (no more chaining of methods, the developer has to declare all the variables before calling the method)
Also returning error codes or messages is not a best practice, the best practice is to use exceptions and exception handling for error reporting, else errors become to easy to ignore and there's more work passing the error info around, while at the same time losing valuable information like stacktrace or inner exceptions.
A better way to declare the method is like this.
public static List<Poll> GetPolls() ...
and for error reporting use exception handling
try
{
var pols = GetPols();
...
} catch (DbException ex) {
... // handle exception providing info to the user or logging it.
}
It depends on what the error message is. For instance, if processing couldn't continue because the database connection wasn't available, etc., then you should throw an exception as other people have mentioned.
However, it may be that you just want to return "meta" information about the attempt, in which case you just need a way to return more than one piece of information from a single method call. In that case, I suggest making a PollResponse class that contains two properties: List < Poll > Polls, and string ErrorMessage. Then have your method return a PollResponse object:
class PollResponse
{
public List<Poll> Polls { get; }
public string MetaInformation { get; }
}
Depends on if an error is a common occurance or if it us truly an exception.
If errors are gunuinely rare and bad then you might want to consider having the method just return the list of polls and throw an exception if an error occurs.
If an error is something that is realtively common part of normal operations, as like an error coverting a string to an integer in the int.TryParse method, the method you created would be more appropriate.
I'm guessing the former is probably the best case for you.
It depends on how frequently the method will fail. In general, errors in .Net should be communicated with an Exception. The case where that rule doesn't hold is when the error condidition is frequent, and the performance impact of throwing and exception is too high.
For Database type work I think an Exception is best.
I'd restate it like this.
public static List<Poll> GetPolls()
{
...
}
It should probably be throwing an exception (the errorMessage) if it fails to retrieve the polls, plus this allows for method chaining which is less cumbersome than dealing with out parameters.
If you run FxCop, you'll want to change List to IList to keep it happy.
I think its fine. I would prefer though:
enum FailureReasons {}
public static IEnumerable<Poll> TryGetPolls(out FailureReasons reason)
So the error strings don't live in the data-access code...
C# Methods should really only do one thing. You're trying to do three things with that method. I would do as others have suggested and throw an exception if there is an error. Another option would be to create extension methods for your List object.
e.g. in a public static class:
public static List<Poll> Fill( this List<Poll> polls) {
// code to retrieve polls
}
Then, to call this, you would do something like:
List<Poll> polls = new List<Poll>().Fill();
if(polls != null)
{
// no errors occur
}
edit: i just made this up. you may or may not need the new operator in List<Poll>().Fill()
Please state your assumptions, constraints, desires/goals, and reasoning; we're having to guess and/or read your mind to know what your intentions are.
assuming that you want your function to
create the polls list object
suppress all exceptions
indicate success with a boolean
and provide an optional error message on failure
then the above signature is fine (though swallowing all possible exceptions is not a good practice).
As a general coding style, it has some potential problems, as others have mentioned.
There is also this pattern, as seen in many Win32 functions.
public static bool GetPolls(out List<Poll> polls)
if(!PollStuff.GetPolls(out myPolls))
string errorMessage = PollStuff.GetLastError();
But IMO it's horrible.
I would go for something exception based unless this method has to run 65times per second in a 3d game physics engine or someting.
Did I miss something here? The question asker seems to want to know how to clean up resources if the method fails.
public static IList<Poll> GetPolls()
{
try
{
}
finally
{
// check that the connection happened before exception was thrown
// dispose if necessary
// the exception will still be presented to the caller
// and the program has been set back into a stable state
}
}
On a design side note, I'd consider pushing this method into a repository class so you have some sort of context with which to understand the method. The entire application, presumably, is not responsible for storing and getting Polls: that should be the responsibility of a data store.

Best way to explain why something failed

Suppose I had the following method in an object:
public class foo
{
public bool DoSomethingAwesome()
{
bool bar = DidSomething() //suppose this sends an email;
return bar;
}
}
If I wanted to provide more detail on why DidSomething returned a false would the best practice be to assign a message to a Property to foo, or assign an Out parameter to DoSomethingAwesome?
I think this depends highly on the framework you're using (i.e. it's a convention).
For Win32 - you had the SetLastError,
GetLastError.
For .NET it's usually
throwing an Exception but that could be
changed to match your circumstances.
Probably an out param would be ok.
If you decide to go with the Exception route, MSDN has an entry with "Design Guidelines for Exceptions". And there's a great discussion in the book "Framework Design Guidlines" - chapter 7, which I highly recommend!
It depends very much on what you're doing, but in the situation given—sending an email—I would throw different exceptions based on what went wrong. As sending an email should work pretty much every time, when something bad happens, I'd want to force the caller to handle it rather than ignoring it by default.
In other situtations, where the chance of failure is high, failure can be ignored, or false doesn't necessarily mean failure, I'd create an enum which has values for each type of failure and one for success, and return that rather than a bool.
Look at my answer here:
Handing exception in BLL and return to client (either winforms or webforms)?
Maybe it helps.
If the false condition is not an "exception" (not rarely but evenly occurs) and then you should not use exceptions. In that case using an out parameter is much better.

Categories

Resources