Your code is the typical example of static factory method.
Factory Pattern is a part of Software Design Patterns, which are general reusable solutions to a commonly occurring problem within a given context in software design. I can suggest you to read Head First Design Patterns which is a very good starter book to understand design patterns.
Couple of suggestions about your code:
- Make the factory method static, it doesn't use any instance variables etc.
- Not related but, you don't need to use a local variable in your factory method, you can directly return the connection.
Now your method looks like this:
static SqlConnection CreateConnection(){
return new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
}
You might wanna check if the ConnectionStrings["IMS"] is null before calling the constructor of SqlConnection. No further error handling is required in this class because it doesn't initiate the connection.
Let's say you want to return an open connection and handle connection errors in the same method:
static SqlConnection CreateConnection()
{
if (ConfigurationManager.ConnectionStrings["IMS"] == null)
{
throw new Exception("Connection string not found in the configuration file.");
}
var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
try
{
sqlConnection.Open();
}
catch (Exception exception)
{
throw new Exception("An error occured while connecting to the database. See innerException for details.", exception);
}
return sqlConnection;
}
If you want, you can create your own exception classes to handle these exceptions later. See ASP MVC N-Tier Exception handling. You can also return null if an exception occurs, but check "Is returning null bad design?" first.