I am using .NET 3.5 C#. I have a simple connection class with only two methods: OpenConnection() and CloseConnection(). I defined this class as Static so that I don't have to create an instance while calling methods. I want to know whether:
(1) I should create an interface with method definitions for OpenConnection and CloseConnection and thereby use this Interface with Connection class. There is no reason to use an interface but I was thinking whether the Connection can be made more professional.
(2) Is it fine to declare this class as Static?
There are two entirely different approaches
Singleton: Single object across the application.
In this case, you will have to take care of the locking mechanism as well.
class Connection
{
public static Connection Instance() {
if (_instance == null) {
lock (typeof(Connection)) {
if (_instance == null) {
_instance = new Connection();
}
}
}
return _instance;
}
protected Connection() {}
private static volatile Connection _instance = null;
}
Implement IDisposable:
Alternatively, you can implement IDisposable in your Connection class, and let it disposed automatically using the using keyword. For instance:
using(Connection c = new Connection(SomeConfiguration)) //Opens the connection.
{
Something(c);
}// Closes the connection. Dispose is implicitly called in the scope of the using statement.
Or if you want Generic Connection class, then Marc has responded with an excellent database connection class example here.
Regarding point 1; you can use interface; iff:
You want loose coupling, componentization, and maintainability in your code.
You want to provide guarantee that the classes shall behave exactly as methods/contracts defined in interface. For instance, in this case, if you extend your class from IDisposable, the interface imposes that not only objects can be disposed without getting compiler errors, but that they should be disposed. So, similar guarantees can be provided in your code by simply adhering to an interface.
You have a team that is going to working on a large module; and you want to keep code consistent; so you can define an interface and add some restrictions, that would help integrate the it easily. For instance:
You know you have a module that is going to handle alot of connections, different types of connections - some of which may be identified later during the development. But what you know for sure is that all types of connection shall be able to Open and Close; and you also want all of the developers to stick to this rule. So you can come up with an interface like:
interface IMyConnection
{
Open();//Opens the connection
Close();//Closes the connection
}
You expect have certain classes that does a lot of complex work and won't be finished before the rest of the project; then rest of the project can use the interface and avoid being dependent on that class.
You plan to deploy your product commercially; and want it to be extendable by 3rd party developers.
If you use interface, you cannot define Static method. (or in other word, static method is always pointing to the class defined, so the interface cannot provide abstraction at this point).
A class can be static, as long as you want everything shared, and extension to it is not necessary. But I would strongly recommend you to look at Singleton Pattern and Abstract Factory as alternative to your design problem.
interface IConnection {
void Connect();
void DisConnect();
}
class TCPCustomConnection : IConnection{
// implement other stuff
// Singleton Pattern
static IConnection Instance {
privateInstance = privateInstance ?? new TCPCustomConnection();
return privateInstance;
}
}
From what you said so far, I don't see how the interface adds value. If it does not add value, it should be eliminated from the design. The interface introduces two new problem: You need to get a pointer to the interface implementation, and usually you want to avoid asking for it repeatedly. So don't do it unless adds value (in a tangible, not metaphysical way) to your design.
An interface might add value if it simplifies unit testing of your code, or if it is important to remove the runtime dependency on the assembly that implements the connection. This is very fashionable these days.
simple a static class is requird, if it just used for demarcating operations like open and close connection, favor simplicity rather, dont code for future scenario until it is absolutely necessary and don't change existing working code till you reach a point where it is absolutely requirea
My advice:
(1) Why you need to write your own Connection class since it's "a simple connection"? None of the built-in classes meets your requirement?
(2) According to MS examples, it's really weird to make Open and Close methods static. We are used to this:
conn.Open();
conn.Close();
instead of:
MyConnection.Open(conn);
MyConnection.Close(conn);
(3) Using interfaces is a good idea, especially IDisposable:
class MyConnection : IDisposable
{
public void Dispose()
{
//close the connection and release resources
}
}
using (MyConnection conn = new MyConnection(connStr))
{
} //automatically Dispose()
If you have different connection type, like UDP, TCP, COM Port, ... using interface is good for manageability, but in the case which you have just one connection there is no need to use interface, also i think using static and singleton is not useful here, you should have a service for your tcp connection to always keep it up, and when you got disconnected you should be able to repair connection. for a good tcp server sample see http://fadd.codeplex.com/SourceControl/changeset/view/58859#1054893.
Even if you think that you'll only ever need one connection, I'd still use an instance class that implements an interface to handle it.
Why?
I can easily swap implementations if I need to (or refactor an existing one).
I can unit test things that depend on the class by mocking the connection.
I can more easily control the lifecycle of the connection (eg by using IDisposable).
Consumers of any API I write can see what my dependencies are.
If the single instance requirement does change, I don't have to unpick all the references to the static/singleton methods.
The testing point here is important: if you use a static reference to a fixed external resource, your code will be virtually impossible to unit test independently of that resource.
See this answer for a similar discussion about static versus instance classes and methods.
Related
To clarify my question, suppose I have the following very basic statistics interface and class:
public interface IStatistics
{
void IncrementPacketsDiscovered();
}
public class Statistics : IStatistics
{
private int numberOfPacketsDiscovered = 0;
public void IncrementPacketsDiscovered()
{
numberOfPacketsDiscovered++;
}
}
Then suppose I have the following class that receives the injected IStatistics object:
public class Reporter
{
private IStatistics _statistics;
public Reporter(IStatistics statistics)
{
_statistics = statistics;
_statistics.IncrementPacketsDiscovered();
}
}
Why is it that I am able to call the IStatistics method IncrementPacketsDiscovered() on the IStatistics object and it automatically knows to fetch the method definition that was implemented in the Statistics class?
Any help would be greatly appreciated. Thank you!
TLDR; because the injected object that implements IStatistics is an instance of the Statistics class, and it is this way because somewhere else you told the dependency resolver to use Statistics whenever you mention IStatistics..
Note that Statistics.IncrementPacketsDiscovered being called is nothing to do with DI per se, you could write this:
IStatistics x = new Statistics();
x.IncrementPacketsDiscovered();
On the outside, x looks like an IStatistics. On the inside, it is a Statistics. If Statistics did something else (other than just implement the interface) it would be easier to see. It would also probably be more clear what's going on if you had something else that implemented IStatistics, like some sort of FakeStatistics that you use in a test scenario - testing is one such valid reason where you'd switch your program back and forth between different suites of objects.
You could just conceive that somewhere outside of all your code is the dependency resolver, a thing created by Microsoft*. It did that first line of code above for you, and later when you said you wanted to have a Reporter it looked and saw "the constructor takes a parameter of anything that implements IStatistics, and I just happen to have an instance of Statistics here that fits that requirement, so I'll pass that into the Reporter constructor.." because that is what it is configured to do/that is its job.
If you had a FakeStatistics that you used for testing, and a context where you reconfigured the injector to create and supply fake objects then it suddenly starts to make sense why it's a useful way to engineer - you don't have to have 100 places where you said new Statistics where you go through and change them all to say new FakeStatistics. It's also useful to be writing a class and suddenly realize "this class needs statistics.." you add a single argument IStatistics x to the constructor, hit Ctrl . and pick the option to add a property for it and that class now has access to a suitable implementation of IStatistics, supplied by the resolver. You don't have to chase up through everywhere you said new MyXClass(param1, param2) and change it to say new MyXClass(param1, param2, someStatistics) because the job of newing all your objects is the responsibility of the resolver
By using interfaces and coding up such that "any object that implements this interface can sensibly be used as an input argument to this class" you then open it up to the possibility that a "class instance lookup and provider service" can wire all your app together just by "rummaging around in its currently configured bag of objects for one that will do the job" (and then you change what's in the bag depending on the context)
So where did you put things in the bag? In the part of the program where you configured the resolver, methods like AddScoped, AddTransient, AddSingleton have the dual purpose of mapping a type of class to a type of interface and also configure what sort of lifetime the instance has- resolvers manage instances for you and create/destroy them over the lifetime you specify by which Add* method you use
* With this statement I am, of course, making a gross assumption as to which injector you're using. There are other DI/IoC frameworks available for C#, created by others. The overarching concept remains the same; the more you can get the computer to write your code for you, the quicker, easier and more reliable it can be. Establishing dependenceies between objects in your program is one such place where it can make sense to hand it off to software rather than writing it yourself
I'm writing a PCL in .NET and I have a wrapper class around HttpClient that loads an HtmlAgilityPack.HtmlDocument from a URI in multiple different methods. It is stateless, so I would really like to make it static, since in my opinion instantiating something with new gives the impression that it contains state. However, I have a couple of interfaces that I want it to inherit from, so it can't be static. This is where I thought of making it a singleton. Here are a few snippets from the code:
public class ConcurrentClient : IAsyncClient<HtmlDocument>
{
private static readonly ConcurrentClient _Instance = new ConcurrentClient();
private ConcurrentClient() { }
public static ConcurrentClient Instance
{
get { return _Instance; }
}
public HtmlDocument LoadUri(string uri)
{
return LoadUriAsync(uri).Result;
}
// ...
public async Task<HtmlDocument> LoadUriAsync(string uri,
Encoding e, NetworkCredential creds, Action<HtmlDocument> prehandler)
{
// ...
}
}
I'm wondering, though, if I should change the beginning parts to this:
private static readonly ConcurrentClient _SharedInstance = new ConcurrentClient();
public static ConcurrentClient SharedInstance
{
get { return _SharedInstance; }
}
The reason for this is I'm not that sure about using the Singleton pattern, mainly because I've rarely seen it in use in other libraries (maybe WinRT's Application.Current?), and I think it would encourage users of my PCL to write coupled code, since it's much easier to just call ConcurrentClient.Instance everywhere than it is to pass it in as a parameter.
However, I do want to encourage the use of a shared instance because excluding the reasons above, there's very little point in calling new ConcurrentClient() because all it does is create more memory overhead. Also, I can't think of a better way to implement inheritance with methods that don't really rely on state.
Your Singleton already implements 2 interfaces. The question really is, where are the dependencies to this Singleton and why are they there ?
If the answer is that these dependencies are there because they need to get to the implementation of those interfaces then I would say that this is wrong.
The whole point of doing a SOLID design is to have dependencies towards interfaces and not towards any concrete implementation. So anyone who needs any of these 2 interfaces should be given those interfaces via dependency injection. So that means that the interfaces would be passed by their constructor or via an extra parameter in a method call, a strategy pattern, ...
Also see this : http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
There can be a reason to make a singleton, but based on your explanation this is not that clear.
Investigate more of your time in using dependency injection. If you have that under control move one step further and investigate on how you can use an inversion of control container.
Also, it's easy to forget DI and passing around the object as a parameter when you can just access it by Singleton.Instance.
You are forgetting about unit testing. If you pass interfaces to your class constructors you can easily mock those interfaces and test your class functionality. With your singleton in place, your classes really need that singleton. Unit testing will be harder.
Of course Instance is easy to access, it's a global and since people revert back to old habits of programming towards objects all the time, that is why it is so popular.
Suppose I want to inherit from System.Data.SqlClient.SqlTransaction which is sealed. Supose I want to just put a wrapper around SqlTransaction and always use MyTransaction instead of SqlTransaction. Is there a way I could potentially cast MyTransaction to SqlTransaction using an Implicit/Widening operator?
You could create a class that has an inner transaction variable and then expose the methods and properties. Kind of like this:
public class MyTransaction
{
System.Data.SqlTransaction myTx = someConnection.CreateTransaction();
public void CommitTransaction() : {
myTx.CommitTransaction()
}
}
You could also make it inherit from DbTransaction and then rewrite the abstract and virtual procedures to use the inner myTx variable, but it starts getting a little complex for no apparent real reason...
If you really want implicit conversion (although I would not recommend it, as it is a horrible idea and a horrible design, IMO), you can do something like this:
class MyTransaction
{
private readonly SqlTransaction _transaction;
public MyTransaction(SqlConnection conn)
{
_transaction = conn.BeginTransaction();
}
public SqlTransaction Transaction
{
get
{
return _transaction;
}
}
public static implicit operator SqlTransaction(MyTransaction t)
{
return t.Transaction;
}
}
If you are just interested in adding additional methods to a class you could use extension methods. That won't give you access to any internal state, or allow you to override behaviors, but it will let you add limited functionality. I'm not aware of any way to inherit from a sealed class.
You could create a true wrapper object as others have mentioned, but you won't be able to use it polymorphically in place of the original object.
OK, so ruling out the inheritance and focusing on the task you really want to solve (based on the comment threads).
I have had success in the past running all calls through a helper library and implementing the logic there. In the past, I have used SqlHelper, which is published in the Microsoft Data Application Block. This is a source module, which you can adapt to your needs. You can add whatever logging or other logic you require.
It also makes the code very readable. You can do things like:
SqlHelper.ExecuteDataset() for queries returning sets of data,
SqlHelper.ExecuteScalar() for queries returning single values,
SqlHelper.ExecuteNonQuery() for commands which have no returns (like INSERT's).
etc.
No, you cannot have your custom class be inherited from SqlTransaction or to have this faked.
However, if the context of what you are doing allows you to use a DbTransaction, you could inherit your custom transaction class from DbTransaction, wrapping up a SqlTransaction inside with whatever other functionality you require.
You do have another option, you could use Reflection.Emit() to add an interface of your choosing to SqlTransaction, and then use that same interface, in your new MyTransaction class and then you can make calls to the interface, instead of the class.
Take care that this will only work within libraries you create, or specifically modify the loaded types using Reflection.
You can create extension methods.
public static class SqlTransactionExtensions
{
public static void DoSomething(this SqlTransaction transaction, int myParameter)
{
// do something here
}
}
The class must be static. Place the magic word this in front of the fist parameter which must be of the type of the class you are extending. You can extend interfaces as well. If you want to use this extension method, then you must have a using namspace with the namespace of this extension class, if it is not defined in the same namespace you are working in.
You can then call the extension method as if it was a regular method of SqlTransaction:
SqlTransaction t = new SqlTransaction();
t.DoSomething(5);
You can define your own MyTransaction class as a wrapper around SqlTransaction. Keep an instance of SqlTransaction in a private field inside MyTransaction. Your wrapper will not be assignment compatible with SqlTransaction, but if you implement the same interfaces SqlTransaction implements you can get pretty close.
I need to create a class that will accept a datasource type (MSSQL, Oracle, Access, Excel, ActiveDirectory, CSV file, Sharepoint etc.), the connection details for that type, and return a connection to that data source.
After that I need to be able to interrogate the data source and return the available fields, and finally be able to extract data from any fields.
I was thinking that this sounds like a job for a interface, as the list of datasource types will grow over time, but I have never used interfaces.
Will this do?:
interface IConnectable
{
void Connect();
}
class SourceMSSQL : RDB, IConnectable{}
class SourceOracle : RDB, IConnectable{}
class SourceAccess : RDB, IConnectable{}
class SourceExcel : RDB, IConnectable{}
class SourceCSVFile: FlatFile, IConnectable{}
class SourceSharePoint: FlatFile, IConnectable{}
class SourceActiveDirectory: FlatFile, IConnectable{}
also, how do I add Read() to that list?
PS: I only need to read, not write.
Yes, you are on the right track. An interface is a specification that allows you to work with an "unknown" class that gives you the service you want without you being tied to which service (in this case which database type) you are using.
In the code you have you would continue to build on you interface with something like:
interface IConnectable {
IConnection Connect();
}
interface IConnection {
IResultSet ExecuteQuery(string query);
}
and then implement these with concrete classes. In addition you need a factory to create whatever class you need:
class ConnectionFactory {
IConnecable CreateConnection(...);
}
this so that you do not have to know which connection to create.
There are some help already present in the .NET framework. There is a class DbConnection with subclasses like SqlConnection that might help out. Also there are frameworks that help you wire up (create classes and associate them together) but that is a more advanced topic which may be something to try out later - begin with creating your own interfaces and implementation for those - that will be easier to understand.
Good thinking! Good luck!
P.S. In order to be able to easily reconfigure your software to create different objects implementing the same interfaces (which usually is a flexibility you want) you do not want to create objects using the constructors directly, instead have one central place where the objects are created. That place is usually referred to as a factory (it creates objects...). The factory can be very simple (maybe just look at a configuration string or a command line argument or whatever controls your behaviour), or more advanced where complex rules dictate which classes should be used in different situations.
There are frameworks that provides factories of different sorts for different situations, structuremap link is one and MEF (included in .NET 4 and is available at link) is another. But do not start with that, it will give you too much to think about at once - you can later on add that given that you are using interfaces to begin with!
Using a Singleton class guarantees one instance of a class to give control to the programmer. Really useful.
I was wondering if for example a Singleton Interface existed in a given framework to bypass the need to create/add one explicitly?
Would be handy to decalre:
public sealed class MySingleton : ISingleton //or a different class
{ ... }
And then expect the class to only ever be instantiated once.
Is this a good idea, or am I thinking a bit off the mark? :)
I was wondering if for example a Singleton Interface existed in a given framework to bypass the need to create/add one explicitly?
It doesn't and can't exist. A singleton basically requires a static Singleton getInstance() method, but because it's static, it cannot be definied as an abstract (interface) method. It also makes sense, there can be only one singleton implementation, not multiple. Abstracting it is pointless.
You'll need to boilerplate complete singletons yourself. I however highly question how that's useful. It's certainly not its sole purpose to prevent stackoverflow or memory errors. Writing good code prevents that. Singletons are only useful if you want to have the enduser to deal with the same instance all the time. Which can be done as good without the singleton pattern by the way. Either just declare it static or make use of the "application scope" concept the average framework can provide you.
Instead of singletons, rather look for inversion of control (dependeny injection). That's by the way also exactly what Spring is doing. They do not use "pure" singletons. It was a poor word choice they made.
See also:
Singletons are evil
Patterns I hate #1: Singleton
Inversion of Control and Dependency Injection pattern
A Spring Singleton is not a Singleton
Singleton does not prevent stack overflow, not sure what you are getting at with that.
For Java, what came to mind is Spring. By default, every Spring bean you write is a singleton. You can use it in 100 places, and they will all be set automagically via injection, and all 100 references will go to the same object (i.e. a singleton). When you set up a project in Spring, you can make any class you want a singleton just by following the conventions.
Google Guice is a dependency-injection framework that supports a #Singleton annotation.
Note that classes annotated with #Singleton aren't "true" singletons - there's nothing stopping client code from creating many instances of such a class. However, Guice-managed dependencies will all share the same instance.
See http://code.google.com/p/google-guice/wiki/Scopes
Maybe not what you're looking for, but here's my favorite version of the singleton pattern in C#. It's thread-safe, uses lazy instantiation, and doesn't require any locks. It's also pretty painless to write... no frameworks needed. ;)
class MyClass
{
// ...
#region Singleton pattern
private MyClass() { }
public static MyClass Instance { get { return Singleton.instance; } }
class Singleton
{
static Singleton() { }
internal static readonly MyClass instance = new MyClass();
}
#endregion
// ...
}
To get the object instance:
MyClass m = MyClass.Instance;
In Java you can do this simply with an enumerated type. You specify the number of instances so that there can be none (also called a utility class), one (also called a singleton) or more as you choose.
public enum MySingleton {
INSTANCE;
}
.NET 4.0 has the Lazy(T) Class, which will lazily-initialize a value on first access, in a thread-safe manner. There are lots of examples at the Lazy Initialization topic.
Also, if you are using Unity, there is a lifetime manager which you can configure with the ContainerControlledLifetimeManager to ensure a single instance.
Ruby has a module called singleton that makes the class which includes it a singleton. This module is built into the standard library.
The intention behind the singleton pattern is "Configure once. Use multiple times". This is typically used to share any kind of data or resources as mentioned in one of the answers above. But it is also useful to enable any kind of "management" application. (think JMX if it is Java)
You have one instance of a certain class that you can use multiple times. Since there is only one instance, by configuring that instance appropriately, you can reflect the configuration changes across the app. Hence the singleton pattern gives the ability to enable a "management dashboard" to your app.
Spring or Spring.NET (the .NET implementation of Spring) are useful for configuring and injecting singletons. The same arguments apply for any kind of dependency injection framework. You should read about dependency injection in general to harness the full power. A true singleton, across multiple JVMs or clusters, is usually harder to create and manage. and might require tool support. In practice, it is not necessary to create and maintain that.
Don't confuse singletons with statics! The construct looks similar but it can be pretty different. Now to drum my own trumpet! Here is a link to an article that I had written about static methods.
public class Singleton<T> where T : class, new()
{
static class SingletonCreator
{
internal static readonly T instance = new T();
}
public static T Instance
{
get
{
return SingletonCreator.instance;
}
}
}
It is lazy and versatile. Define constructors on demand.