开发者

Improving a connection class with methods: Open and Close

开发者 https://www.devze.com 2023-01-23 02:51 出处:网络
I am using .NET 3.5 C#. I have a simple connection class with only two methods: OpenConnection() and CloseConne开发者_JAVA技巧ction(). I defined this class as Static so that I don\'t have to create an

I am using .NET 3.5 C#. I have a simple connection class with only two methods: OpenConnection() and CloseConne开发者_JAVA技巧ction(). 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消