In this particular application, there is no separate data layer and the data access code is in the Entity itself. For example, consider a Customer entity, then in the Customer.cs file where the members and properties are defined, you have methods to load the Customer object as below
public bool TryLoad(int customerID, out Customer customer)
{
bool success = false
try
{
//code which calls the db and fills a SqlDataReader
ReadDataFromSqlDataReader(reader);
success = true;
}
catch(Exception ex)
{
LogError();
success = false;
}
return success;
}
Now, in the ReadDataFromSqlDataReader(reader), tryparse is used to load data from the reader into the object. e.g.
public void ReadDataFromSqlDataReader(reader)
{
int.TryParse(reader["CustomerID"].ToString(), out this.CustomerID);
PhoneNumber.TryParse(reader["PhoneNumber"].ToString(), out this.PhoneNumber);
... similar TryParse code for all the other fields..
}
Is using TryParse to read all the properties from the reader a good practise? A dev told me that its done this way as TryParse has a better performance than int.Parse. But wouldnt you want an exception to be throw when the value you are reading from the db does not conform to what your code expects? I mean in this case, if there is a wrong phone number in the db then perhaps the object shouldn't be initialized at all instead of loading an object with an empty phone number?
Yes, following the fail-fast principle, you would want an exception to be thrown the moment a value comes back that cannot be converted into the expected type.
If one of these operations fails and you continue as if nothing happened, you are likely to get weird errors that are hard to catch and hard to pinpoint: objects being added to the database when they should have been updating an existing row, data mysteriously disappearing, dogs and cats living together... you get the idea.
On the other hand, if you throw an exception immediately, you know exactly where your problem is and you can catch it and fix it before it becomes worse.
TryParse will work faster than Parse in case of failure simply because it doesn't have to throw an exception (which can be expensive), but if you're assuming that things will succeed (which this code is doing by not using the result of the parse), you should get equivalent performance using Parse.
What sort of validation are you doing when the data is being inserted and/or updated?
As long as you are applying some form of validation here, I personally would not be validating the data coming out of the Database as you should be confident that you are only putting in valid data.
Effective validation be performed when data is inserted into the database. It's not a good design with which bad data could be entered in the database. If database contains bad phone number, user should be asked to enter phone number again if its mandatory and if phone number is not that important, you could initialize phone number to null in case of bad data.
I wouldn't be using TryParse for that.
If my db had rubbish in it, I'd want that addressed.
If the data was ambiguous in terms of parsing (e.g. Varchar with int or double in it as a string)
I'd want to sort out my schema, TryParse as type detection would be a quick and simple hack.
If you would handle it, well yes you should throw an exception. But if you don't care about the exception and if you would filter the right data and use it (in this case non zeros) you can skip.
As, TryParse returns Boolean value. So, I can ByPass/Continue the Upcoming Logic/Any Database request on the basis of Boolean Value. I will not let the exception to occur in such scenaria. For that I will do the logging etc.
Parse
Throws an exception.
Use it if you are sure the value will be valid
TryParse
Returns a bool indicating whether it succeeded
It just try/catch internally that why is implemented without exceptions so that it is fast
Use it in case the value may be InValid
Related
Okay, I have some very simple code which I will post below. Essentially, I have a connection to a database and I want to map a subset of columns in a query to a particular class. The problem is that it is possible for these to be null.
I would like to know if it is possible if an exception is thrown at a particular line, can we resume the entire block from the next line.
So if this code below was to execute and Line 6 catches an error. Is there an elegant way to catch the exception and make the code resume running at line 7. Essentially making it as though line 6 was never executed.
private static Column MapTableToColumn(OracleDataReader reader){
Column c = new Column();
c.ColumnName = Convert.ToString(reader["COLUMN_NAME"]);
c.DataType = Convert.ToString(reader["DATA_TYPE"]);
c.DataLength = Convert.ToInt32(reader["DATA_LENGTH"]);
c.DataPrecision = Convert.ToInt32(reader["Data_Precision"]);//<---Line 6
c.DataScale = Convert.ToInt32(reader["Data_scale"]);//<--- Line 7
c.AllowDBNull = Convert.ToBoolean(reader["ALLOW_DB_NULL"]);
c.IsReadOnly = Convert.ToBoolean(reader["IS_READ_ONLY"]);
c.IsLong = Convert.ToBoolean(reader["IS_LONG"]);
c.IsKey = Convert.ToBoolean(reader["IS_KEY"]);
c.KeyType = Convert.ToString(reader["KEY_TYPE"]);
c.IsUnique = Convert.ToBoolean(reader["IS_UNIQUE"]);
c.Description = Convert.ToString(reader["DESCRIPTION"]);
return c;
}
It is important to note I am not asking for best practice, it is not something I intend to use in actual code (unless its absolutely genius). I simply want to know if this is possible and how one would go about doing this if it were.
My Research
Most of my research is proactive as opposed to reactive. I would attempt to know if it is possible for the given field to be null before it is read from. If it is, then I'd do a check to determine if the field is null and then set it to a default value. It essentially avoids the possibility of an error happening which I believe is a very good solution. I just wanted to attempt this as I know that when an exception is thrown, the most inner exception contains the line number at which it was thrown. Based on this if you put the exception inside of the class throwing the exception you should hypothetically be able to use reflection in order to continue running from its last point. I'm just not sure how you'd go about doing this. I've also considered the possibly of putting try catches around every single line which I think would be very effective; however, I think that it would be very ugly.
No, what you are asking for is not possible in C#.
Instead the proper solution to this problem is to use better parsing methods that won't throw exceptions in the first place. If your input values can be null, then use parsing methods that can accept null values.
The first thing you probably need to do is use nullable types for your int/bool fields, so that you can support null values. Next, you'll need to create your own methods for parsing your ints/bools. If your input is null, return null, if not, use int.TryParse, bool.TryParse (or as for each if your input is the proper type, just cast to object).
Then by using those methods, instead of Convert, you won't be throwing exceptions in the first place (which you shouldn't be doing here even if it could work, because exceptions are for exceptional cases, not expected control flow).
If the exception is expected then it is not exceptional. Never never never catch a null reference exception. A null reference exception is a bug. Instead, write code to avoid the bug.
You can easily write helper methods that test for null, or use methods like Int32.TryParse that can handle malformed strings.
Check for IsDBNull
SqlDataReader.IsDBNull Method
And Reader has methods for each SQL datatype
For example
SqlDataReader.GetSqlBoolean
If the data is in SQL as string (char,nchar) then first check for null and then TryParse
For example
DateTime.TryParse
And ordinal position is faster
This is a sample for a nullable Int16
Int16? ID;
ID = rdr.IsDBNull(4) ? (Int16?)null : rdr.GetInt16(4);
If you want a default
Int16 ID;
ID = rdr.IsDBNull(4) ? 0 : rdr.GetInt16(4);
You'd need a try/catch around every single variable assignment, and you'd need to initialize all your Column instance values before you tried. This would be relatively slow.
As for reflection based on the line number: I wouldn't rely on the line number because one simple, innocent change to the code will throw it off completely.
I'd check for nulls specifically. If you expect them you can't hardly call them "exceptions". The method that does that is reader.IsDBNull. It takes the column index (not the column name) so you'll need to resolve the index using reader.GetOrdinal:
if (reader.IsDBNull(reader.GetOrdinal("Data_Precision"))) {
// It's null
} else {
// It's not null
}
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."
I am calling a stored procedure that inserts data in to a sql server database from c#. I have a number of constraints on the table such as unique column etc. At present I have the following code:
try
{
// inset data
}
catch (SqlException ex)
{
if (ex.Message.ToLower().Contains("duplicate key"))
{
if (ex.Message.ToLower().Contains("url"))
{
return 1;
}
if (ex.Message.ToLower().Contains("email"))
{
return 2;
}
}
return 3;
}
Is it better practise to check if column is unique etc before inserting the data in C#, or in store procedure or let an exception occur and handle like above? I am not a fan of the above but looking for best practise in this area.
I view database constraints as a last resort kind of thing. (I.e. by all means they should be present in your schema as a backup way of maintaining data integrity.) But I'd say the data should really be valid before you try to save it in the database. If for no other reason, then because providing feedback about invalid input is a UI concern, and a data validity error really shouldn't bubble up and down the entire tier stack every single time.
Furthermore, there are many sorts of assertions you want to make about the shape of your data that can't be expressed using constraints easily. (E.g. state transitions of an order. "An order can only go to SHIPPED from PAID" or more complex scenarios.) That is, you'd need to use involving procedural-language based checks, ones that duplicate even more of your business logic, and then have those report some sort of error code as well, and include yet more complexity in your app just for the sake of doing all your data validation in the schema definition.
Validation is inherently hard to place in an app since it concerns both the UI and is coupled to the model schema, but I veer on the side of doing it near the UI.
I see two questions here, and here's my take...
Are database constraints good? For large systems they're indepensible. Most large systems have more than one front end, and not always in compatible languages where middle-tier or UI data-checking logic can be shared. They may also have batch processes in Transact-SQL or PL/SQL only. It's fine to duplicate the checking on the front end, but in a multi-user app the only way to truly check uniqueness is to insert the record and see what the database says. Same with foreign key constraints - you don't truly know until you try to insert/update/delete.
Should exceptions be allowed to throw, or should return values be substituted? Here's the code from the question:
try
{
// inset data
}
catch (SqlException ex)
{
if (ex.Message.ToLower().Contains("duplicate key"))
{
if (ex.Message.ToLower().Contains("url"))
{
return 1; // Sure, that's one good way to do it
}
if (ex.Message.ToLower().Contains("email"))
{
return 2; // Sure, that's one good way to do it
}
}
return 3; // EVIL! Or at least quasi-evil :)
}
If you can guarantee that the calling program will actually act based on the return value, I think the return 1 and return 2 are best left to your judgement. I prefer to rethrow a custom exception for cases like this (for example DuplicateEmailException) but that's just me - the return values will do the trick too. After all, consumer classes can ignore exceptions just as easily as they can ignore return values.
I'm against the return 3. This means there was an unexpected exception (database down, bad connection, whatever). Here you have an unspecified error, and the only diagnostic information you have is this: "3". Imagine posting a question on SO that says I tried to insert a row but the system said '3'. Please advise. It would be closed within seconds :)
If you don't know how to handle an exception in the data class, there's no way a consumer of the data class can handle it. At this point you're pretty much hosed so I say log the error, then exit as gracefully as possible with an "Unexpected error" message.
I know I ranted a bit about the unexpected exception, but I've handled too many support incidents where the programmer just sequelched database exceptions, and when something unexpected came up the app either failed silently or failed downstream, leaving zero diagnostic information. Very naughty.
I would prefer a stored procedure that checks for potential violations before just throwing the data at SQL Server and letting the constraint bubble up an error. The reasons for this are performance-related:
Performance impact of different error handling techniques
Checking for potential constraint violations before entering SQL Server TRY and CATCH logic
Some people will advocate that constraints at the database layer are unnecessary since your program can do everything. The reason I wouldn't rely solely on your C# program to detect duplicates is that people will find ways to affect the data without going through your C# program. You may introduce other programs later. You may have people writing their own scripts or interacting with the database directly. Do you really want to leave the table unprotected because they don't honor your business rules? And I don't think the C# program should just throw data at the table and hope for the best, either.
If your business rules change, do you really want to have to re-compile your app (or all of multiple apps)? I guess that depends on how well-protected your database is and how likely/often your business rules are to change.
I did something like this:
public class SqlExceptionHelper
{
public SqlExceptionHelper(SqlException sqlException)
{
// Do Nothing.
}
public static string GetSqlDescription(SqlException sqlException)
{
switch (sqlException.Number)
{
case 21:
return "Fatal Error Occurred: Error Code 21.";
case 53:
return "Error in Establishing a Database Connection: 53.";
default
return ("Unexpected Error: " + sqlException.Message.ToString());
}
}
}
Which allows it to be reusable, and it will allow you to get the Error Codes from SQL.
Then just implement:
public class SiteHandler : ISiteHandler
{
public string InsertDataToDatabase(Handler siteInfo)
{
try
{
// Open Database Connection, Run Commands, Some additional Checks.
}
catch(SqlException exception)
{
SqlExceptionHelper errorCompare = new SqlExceptionHelper(exception);
return errorCompare.ToString();
}
}
}
Then it is providing some specific errors for common occurrences. But as mentioned above; you really should ensure that you've tested your data before you just input it into your database. That way no mismatched constraints surface or exists.
Hope it points you in a good direction.
Depends on what you're trying to do. Some things to think about:
Where do you want to handle your error? I would recommend as close to the data as possible.
Who do you want to know about the error? Does your user need to know that 'you've already used that ID'...?
etc.
Also -- constraints can be good -- I don't 100% agree with millimoose's answer on that point -- I mean, I do in the should be this way / better performance ideal -- but practically speaking, if you don't have control over your developers / qc, and especially when it comes to enforcing rules that could blow your database up (or otherwise, break dependent objects like reports, etc. if a duplicate key were to turn-up somewhere, you need some barrier against (for example) the duplicate key entry.
I have a few functions on Data access layer
public Order RetrieveById(int id)
public List<Order> RetrieveByStatus(OrderStatus status)
Now i am bit confuse on exception raising.
In case of RetrieveById function, id which is less than 1 is an invalid id therefore i feel like raising an exception. And i feel like returning null for the Id which doesn't exist in the database. Then it feels like i am over complicating.
In case of RetrieveByStatus, i feel like returning a empty list when there is no data in the database for that status.
However i have seen that some people raising an exception when RetrieveById cannot return anything but then RetrieveByStatus should not raise exception when there is no record or should it?
Could anyone please clarify these concepts for me?
In the first case i would possibly go for a exception and handle myself,instead of returning null.What if your first method is used in a way that the returned object is saved to a Order reference.There is a very high chance of NullReferenceException being thrown,when someone tries to call a method or property on that object.
For the second method i would go for a empty list as some have suggested.
I would prefer to return null in the first case and an empty list
in the second case.
But if you want to raise exception then You can raise exception for public Order RetrieveById(int id) because it means that id is not valid as calling the first method means that you know the id and the it needs to be there.
In the second case the OrderStatus might be valid and there is not record found against it so returning an empty list is a good idea.
Read MSDN first: Creating and Throwing Exceptions (C# Programming Guide). It lists both situations when you are expected to throw an exception, and when to avoid it.
Also take into account What is the real overhead of try/catch in C#?
In any case you'll have to process either null return or an exception thrown
As for myself, I'd prefer in both your methods not to throw exception explicitly. I'd say, there is nothing bad, if your method returns null, if it failed to find an object by id. Whereas the RetrieveByStatus method could return an empty collection, not null.
Besides you could follow the pattern used in LINQ, where you have, say, Enumerable.First and Enumerable.FirstOrDefault methods (either throwing an exception or returning null), so you could use the appropriate one in a certain situation, when the id is 100% valid or when on the contrary it could be missing. While methods returning a sequence of elements don't throw exceptions if the sequence to return appears to be empty; consider Enumerable.Where.
I like to avoid returning null whenever possible, because NullRefExceptions are much more cryptic than a specific exception, say OrderNotFoundException. Also, code gets pretty obtuse when you have to constantly expect entities to be null. This ought to be an exception case anyway -- where did you get that id if it doesn't exist in the db?
On the cases you suspect this is more likely to throw an error, you could add a DoesObjectExist or TryGet type method (or even extension method).
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.