Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I recently started to use c# to interface with a database, and there was one part of the process that appeared odd to me. When creating a SqlCommand, the method I was lead to took the form:

SqlCommand myCommand = new SqlCommand("Command String", myConnection);

Coming from a Java background, I was expecting something more similar to

SqlCommand myCommand = myConnection.createCommand("Command String");

I am asking, in terms of design, what is the difference between the two? The phrase "single responsibility" has been used to suggest that a connection should not be responsible for creating SqlCommands, but I would also say that, in my mind, the difference between the two is partly a mental one of the difference between a connection executing a command and a command acting on a connection, the latter of which seems less like what I have been lead to believe OOP should be. There is also a part of me wondering if the two should be completely separate, and should only come together in some sort of connection.execute(command) method. Can anyone help clear up these differences? Are any of these methods "more correct" than the others from an OO point of view?

(P.S. the fact that c# is used is completely irrelevant. It just highlighted to me that different approaches were used)

share|improve this question

1 Answer 1

Since commands are useless without connections, the fact that the creation of commands is related to an instance of the connection makes sense.

Please note than in addition to the constructor of SqlCommand there is a method called CreateConnection on all IDbConnection instances letting you create a command "Java-style":

IDbCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "select * from mytable";

This code works with any RDBMS, not only the SQL Server, because an Oracle connection would create an Oracle command, a Sql Server connection would create a SQL Server command, and so on.

The pattern is called a Factory Method, it is instrumental in letting you program to an interface.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.