Once I read an MSDN article that encouraged the following programming paradigm (its not 100% true... see edit):
public class MyClass
{
public void Method1()
{
NewCustomException();
}
public void Method2()
{
NewCustomException();
}
void NewCustomException()
{
throw new CustomException("Exception message");
}
}
Do you think this paradigm makes sense? Wouldn't it be enough to store the exception message in a static const field and then pass it to the exception's constructor, instead of encapsulating the whole exception throw?
EDIT:
Use exception builder methods. It is
common for a class to throw the same
exception from different places in its
implementation. To avoid excessive
code, use helper methods that create
the exception and return it.
I just noticed (see citation), that the article tells to return an exception:
public class MyClass
{
public void Method1()
{
throw NewCustomException();
}
public void Method2()
{
throw NewCustomException();
}
CustomException NewCustomException()
{
return new CustomException("Exception message");
}
}
What do you think about this?
My understanding is that passing an exception instance around is a faux pas if for no other reason than you lose the stack trace associated with the exception. Calling another method would change the stack trace and thereby make it effectively useless. I'd recommend at a minimum getting the stack trace off the exception and passing it as an argument to some helper if that's the road you're going to go down.
That's a refactor too far in my book. You have to go back up a line in the stack trace to see exactly where the problem occured. If your custom exception is always using the same message, put it in the CustomException class. If it's only the same within the code you've quoted, then yes, put it in a const field (you can't have static const - it's implicitly static).
Another problem you get doing that is that there will be lots of places where you wont even be able to throw an exception because the compiler wont allow it. Consider these two methods added to your class:
public string GetFoo1(bool bar)
{
if (bar)
return "";
else
NewCustomException();
}
public string GetFoo2(bool bar)
{
if (bar)
return "";
else
throw new CustomException("Exception message");
}
GetFoo1 will not compile while GetFoo2 will.
I would have a method that builds an Exception, rather than one that throws it. As in the sample below. I seem to remember seeing a Microsoft guideline that recommended this, but I can't remember where.
With this technique, if you want to change the exception type for any reason, you only need to do so in one place (e.g. a change from ConfigurationException to ConfigurationErrorsException when upgrading from .NET 1.x to .NET 2.0).
Also you respect the DRY principle by having a single copy of the code that builds the exception with its message and any other data included in the exception.
You obviously wouldn't do this in trivial cases (e.g. you wouldn't replace throw new ArgumentNullException("myParamName") by throw BuildArgumentNullException("myParamName"))
private static Exception BuildSomeException(... parameters with info to include in the exception ...)
{
string message = String.Format(...);
return new SomeException(message, ...);
}
...
throw BuildSomeException(...);
I don't see the point of making a method that simply throws an exception. But, I do think trowing custom exceptions has value. If all of the exceptions you throw are children of a custom exception, it allows you to quickly see if the thrown exception is one you are accounting for or something you have not handled yet. Also, you can then catch MyBaseException and it is not as bad as catching Exception.
It is handy to do this if you don't know how you plan to handle exceptions, exactly. Do you want to just throw it? Or perhaps later you are going to log the exception somewhere then throw it? Or maybe pass some arguments (i.e. method name, etc.) that get bundled in with the exception?
In this case, creating a separate method that handles the exception situation is convenient when you want to change it.
I don't usually bother with this - instead, just figure out upfront how you are going to handle exceptions (i.e. what string information you are going to putin the message).
I generally prefer to store exception messages as resources. That serves several purposes:
If the requirement comes down to localize exception messages, it's a no-brainer.
Exception messages tend to be more standardized across developers since it's extra work to create a new, but only slightly different message.
If you ensure that messages are referenced by an identifier, and include the identifier with the exception when it's thrown, then tracing a message to the code that threw it is easier.
Downside is it does require (just) slightly more effort up front than hard-coding the messages.
Related
I've read many sites and other responses on StackOverflow, but I still haven't grasped the the importance of exception handling and why we "throw" them.
For this post, my understanding of an exception can best be described as:
"An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running..." https://www.tutorialspoint.com/csharp/csharp_exception_handling.htm
When handling exceptions, I often see the following code snipets:
try
{
// Do something that causes an Exception
}
catch (Exception)
{
// Could have error logging here
throw;
}
If you do not perform any error logging, why have the "try/catch" and "throw" statement? The code will still throw an exception regardless of whether I try/catch. I must be missing something. What does "throwing" do?
I've included a basic divide by zero scenario in the following:
https://repl.it/BjgV/24. When you remove the "try/catch/throw" you see the same results.
Something to keep in mind is not only that caught exceptions can be used for logging errors, they can be used for handling errors that might arise.
Let's say you have some kind of Widget object, that has properties you initialize via arguments to a constructor:
public class Widget
{
public string Name;
Widget(string widgetName)
{
if (widgetName != "")
Name = widgetName;
else
throw new ArgumentException("Name must be provided for widget.");
}
}
In this case, we have a situation where we want to require our Widget have a name when it's instantiated - we check the argument to see if it's blank, and we throw an ArgumentException to indicate that something is wrong with one of the arguments to the constructor, as well as include a helpful message about what specifically went wrong.
This means we can then have context-specific validation logic in a wrapper, rather than having to have everything crammed into our base Widget class:
public Widget ForCaseA (string widgetName)
{
Widget w;
try {
w = new Widget(widgetname);
}
catch (ArgumentException as argEx) // We're specifically catching the subtype of ArgumentExceptions; generic Exceptions or other types of exception wouldn't be caught here and would bubble up out of this try/catch block.
{
// At this point, we could look at the specific data in the exception object to determine what needs to happen to resolve the exception. Since there's only one argument and it's throwing an ArgumentException, we know it's going to be a problem with a bad widgetName. In this case, we can say 'well, in this specific case, we want to give it a default widget name'.
w = new Widget("DefaultName");
}
return w;
}
One of the ways catching exceptions by type becomes exceptionally useful is when you use inheritance to create your own types based off the generic Exception class; e.g. giving your Widgets a WidgetException. This lets you catch issues specific to your class/entity (like the widget's name), but doesn't have to handle issues that fall outside the scope of the Widget itself.
"Throwing" is sometimes (in non-oop languages) the same as "raising" an error.
If we catch an exception, we might want to bubble that up to some method higher in the callstack, and perhaps generalize it more in the process. Thus, we might use something like:
try { doSomething(); }
catch (VerySpecificException ex) {
throw new SomeGenericException(ex);
}
This allows us to expect only generic exceptions in the higher-level programming, while maintaining a full stack trace and inner exceptions so we can see where it came from.
Throw, on it's own (such as in your example), simply pushes the error up to the next caller, with no changes. In your exact example, you might just leave out the try/catch altogether, as the result will be the same (the exception gets pushed to the next block: excepting maybe if you have some AOP or weaving in there to handle it, but that's a bit beyond this answer I think).
If there's no try/catch block, the exception is pushed back up to the next method in the callstack. If there's no try/catch blocks anywhere, the exception is said to be "unhandled", and your application crashes. There's no excuse for an unhandled exception to make it to the top.
Specifically regarding this part:
If you do not perform any error logging, why have the "try/catch" and "throw" statement?
Aside from logging the exception, in some situations you may want to:
Wrap the exception in a meaningful user-defined exception which you throw to raise some error.
Release certain resources just in case the exception happens and bubble it up for potential handling somewhere else.
These are just two examples.
So, if I recall correctly, I seem to remember seeing that there were some new annotations added to C# in 4.5 that allow you to pinpoint exactly where an exception was thrown (class, method, line) via a logger or something. But prior to that, is there any built-in way to at least identify the class and method from which the exception was thrown from the actual exception object without having to parse the stack trace? I'd like to be able to use exception object to say, output a message to a log that says something like "Exception was thrown at MyProject.MyClass.MyMethod(int, string). Message: <exception message>
I realize there are some 3rd party libraries out there that can help with this, but I'd rather keep it simpler if possible while learning a bit more about the FCL. The intent isn't to change what an exception is, but rather to make them more useful in unhandled situations. For instance, an unhandled exception is thrown and caught by a filter. The filter logs the exception and rethrows it. It would be nice if the log that is created can state "It was thrown over here, see the full stack trace for more info." That would make it quicker for us to view the where without having to swim through the stack trace which, in some cases (at least for some of our older stuff) can be very misleading, resulting in chasing our tails only to discover that we would have found the problem quickly if we new exactly where to start.
Use System.Diagnostics.StackTrace if you really need to parse out the individual frames from an Exception object:
using System;
using System.Diagnostics;
public class Program
{
public static void Main(string[] args)
{
try
{
Thrower();
}
catch (Exception e)
{
var trace = new StackTrace(e);
Console.WriteLine(trace.GetFrame(0).GetMethod());
}
}
private static string Thrower()
{
throw new Exception("Boom");
}
}
The feature you are referring to is called Caller Info Attributes and doesn't really have anything to do with exceptions, per se. It is general feature designed mostly for troublshooting. The information is inserted into the assembly at compile time when you use it, similar to __LINE__, __FILE__, __FUNCTION__ macros in C++.
For the source of exception you may look on Exception.Source property, which provides an information like:
The name of the application or the object that causes the error.
You don't need to parse stack trace, it's just a string with all data, which may become usefull in certain cases. Remember that exception ocures in exceptional cases and you need as much information as it can be get.
Should I catch exceptions in my method for "purely documenting" purposes, thus encapsulating the error-documentation inside the method itself, or is that responsibility of the caller?
Suppose I call numerous other methods in my EncryptPackage() method, including the framework ones, which potentially throw numerous exceptions. I wrap everything in using blocks, so no need to catch exceptions for cleanup (or I use try/finally for cleanup). Should I catch the exception anyway, and provide the details about the context of that method, or is it the responsibility of caller method?
Here is the case one:
[Serializable]
class TestClassException : Exception
{
public TestClassException() : base() { }
public TestClassException(string message) : base(message) { }
public TestClassException(string message, Exception innerException) : base(message, innerException) { }
}
class TestClass
{
public TestClass() { }
public void EncryptPackage()
{
try
{
DoSomething();
DoAnotherThing();
}
catch (Exception ex)
{
throw new TestClassException("Error occurred during package encryption", ex);
}
}
}
class ConsumerExample
{
public ConsumerExample() { }
public void DoSomeStuff()
{
TestClass testClass = new TestClass();
try
{
testClass.EncryptPackage();
}
catch (TestClassException ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
}
In this code, notice how the EncryptPackage() method catches all possible exceptions, just to "decorate the error text", with a "Error occurred during package encryption" text. EncryptPackage() here encapsulates the error-description logic.
And here is another technique:
class TestClass2
{
public TestClass2() { }
public void EncryptPackage()
{
DoSomething();
DoAnotherThing();
}
}
class ConsumerExample2
{
public ConsumerExample2() { }
public void DoSomeStuff()
{
TestClass testClass = new TestClass();
try
{
testClass.EncryptPackage();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Error occurred during package encryption.\r\n\r\n" + ex.ToString());
}
}
}
In this example, EncryptPackage() does not catch anything, because the caller documents the error case anyway with "Error occurred during package encryption.\r\n\r\n" message.
Please note that this is a very simplified example, in real world there will be numerous hierarchical classes, and exceptions will be propagating through the long call stack, so which method of catching exceptions is preferred? Second approach seems "cleaner", because the exception is handled in a layer where some "actual handling" (e.g. displaying to user) is going to take place. Call stack information would be preserved in exception object, so technically it will be possible to find out where exactly the exception was thrown. But... that does not seem as "well-documenting" as the first approach, where each level of abstraction adds its own description to the error, preserving the previous exception in an innerException member. In this case, when the execution leaves the TestClass layer, it already contains detailed description of the error that happened within this class. So this feels to be the better encapsulation of error-handling logic.
Which one to use?
There is a chapter on this in Effective Java:
Higher layers should catch lower-level exceptions and, in their place,
throw exceptions that can be explained in terms of the higher-level
abstraction. This idiom is known as exception translation.
I prefer your second example, mainly because it can signicantly reduce the amount of error handling code you have to write, especially if you are writing custom exceptions - with the first example you could end up with a lot of custom exception classes which do not give much benefit (you already have the call stack to tell you where the exception came from).
You might think it is nice to have a more descriptive error message, but who benefits from this? The end-user? Should you even be displaying exception messages to your user (and what language are you going to use)? A lot of the time the user just needs to know that there has been an internal error, and they should give up (restart), or try again. Do you the developer benefit? You are probably going to end up examining the call stack anyway with the source code in front of you, so you don't really need a more descriptive message, you can see for yourself what the code is doing at that point.
This is not a hard and fast rule. Most of the time I only catch exceptions at the top level, where I log them and report an error to the user. If you are reporting the exception directly to the user, then often the original exception does not benefit from translation, e.g., if you try to open a non-existent file, then the System.IO.FileNotFoundException is descriptive enough so why translate it to something else? Do you really want to make the same judgement call ("I know better than the library author so I am going to translate their carefully crafted exceptions") for all of the gazillions of exceptions out there? I only catch exceptions lower down if I want to recover from them (generally not possible), or, very rarely, I want to translate them to a more descriptive exception.
In a layered architecture, it can make sense to translate exceptions between the layers, e.g., catch exceptions coming out of the data access layer to a form suitable for the application layer, and similarly between the application layer and the user interface, but I don't know if you are working on that type of system.
If you want to document your exceptions, you should use the exception tag in the xml documentation for the method. This can then be used to general help files from the documentation, e.g., using SandCastle.
As per #Sjoerd above, translate exceptions so they are in the same level of abstraction. In your case EncryptPackage should translate any lower-level exceptions itself, NOT the caller.
Say the lower-level exceptions were from a DB layer (say DBException). Would the caller expect to understand DBException? The answer is NO: the caller wants to encrpt a package, not a DBException. The lower-level exceptions should be chained INSIDE the higher-level exception for debugging purposes.
Finally, I know TestClassException is an example, but make sure the exception class describes the problem clearly: I, personally, don't like bland, generic exception classes (except to make a common base-class for other exceptions).
You should try/catch in few, easily distinguished situations:
any method that can be invoked "externally", such as your app's entry point, UI events, multi-threaded calls and others. Put some log output or message on each and every catch you have. This will prevent your app from crashing (for the most part) as well as provide you or the user with some feedback on how to fix the problem.
when you can really handle the exception. This means your app can, for example, opt for a secondary database or server URL, apply a different processing etc.
when you want to prevent something optional from ruining the main workflow, for example failing to delete your temp file shouldn't cause your process to fail.
there are probably some other places where you'll need a try/catch but these should be rare
Always combine error handling with a decent way of logging and/or messaging the user, don't let any exceptions info disappear because that's how you get apps and don't behave well for "no apparent reason" - at least the reason should be made apparent.
Also - don't use exceptions to control your workflow. There really shouldn't be any "throw"s unless there's absolutely no other way of doing something.
When should I create my own custom exception class rather than using a one provided by .Net?
Which base exception class should I derive from and why?
Why create your own exception?
You create your own exception so that when you throw them, you can have specific catches and hence differentiate them from system thrown (unhandled) exceptions.
What class should you derive it from?
Earlier, it was standard practice for custom exceptions to be derived from ApplicationException class but over time, MS recommendations have changed encouraging developers to derive from System.Exception itself rather than ApplicationException
This may seem a bit obvious but you should create an exception when no built in exceptions make sense. Typically I will define a base exception for a library I am working on.
public class MyLibraryException : Exception
{
// .....
}
Then I will create an exception for situations that may arise when using the library.
public class SomethingHorribleException : MyLibraryException
{
// .....
}
Then the client can always know that my library will throw something that inherits MyLibraryException.
The goal of exception handling should be to create a clear understanding of what went wrong. Therefore, you should define your own exception any time the provided exceptions do not provide that clear understanding.
For example, I'm writing an application which converts Arabic Numerals to Roman Numerals. One of the constraints in this application is that Roman Numerals must fall within the range 0 < x < 4000.
private string ToRoman(int number)
{
if (number > 0 && number < 4000)
{
//ConvertHere
}
else
{
//Custom exception used for readability purposes.
throw new NumeralOutOfRangeException();
}
}
As for which base class to use, Microsoft recommends that user defined exceptions subclass Exception. (http://msdn.microsoft.com/en-us/library/seyhszts.aspx)
One reason to create your own exception is to be able to isolate them for catching. For example:
try {
// do stuff
} catch (MyCustomException e) {
// handle this known exception
}
All other exceptions can bubble up and be handled at another level.
The answers so far all look good, but I would also add:
To hide implementation details that might otherwise be exposed because you need to handle those exceptions.
E.g. You don't want your UI to catch SQLException. You should throw your own exceptions out of your data access code and let your UI deal with those. If you changed to a non database provider for data storage (e.g. XML, file system, etc), you would not need to change your UI code.
However, I would only do that if I was handling them in my UI code explicitly.
I'd create my own excpetion class if i wanted to add other properties to it such as variables, location, user name, num returned records etc.
essentially i'd create a class that would narrow down what the error was and how to re-create it.
edit
oh and you could add validation errors to an exception class that can be passed to the front end to show the errors.
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.