ADO.NET and an Anti-Pattern example

Posted by salo 0 comments

I’ve been coding some ADO.NET examples in the past days and realized a thing which I can only call a *big* anti-pattern in the ADO.NET code. I’m really looking forward to seeing the .NET Framework code (when it becomes available). Hopefully I’ll find some justification in the code that can be considered as an excuse for the presence of this anti-pattern!

Let’s take a short look at the following code:

private String sqlConnectionString;
private SqlConnection sqlConnection;
private SqlDataAdapter sqlDataAdapter;
private String sqlSelectCommandString;
private SqlCommand sqlSelectCommand;
private SqlCommandBuilder sqlCommandBuilder;

Here we have setup the variables that we shall use: we see the SqlConnection, SqlDataAdapter, SqlCommand and SqlCommandBuilder objects. Further on, we use these as follows:

sqlConnection = new SqlConnection(sqlConnectionString);
sqlSelectCommand = new SqlCommand(sqlSelectCommandString, sqlConnection);
sqlDataAdapter = new SqlDataAdapter(sqlSelectCommand);
sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

 

The big anti-pattern that I am talking about is the last line of code, on which we create the SqlCommandBuilder object. The constructor of the SqlCommandBuilder object takes an SqlDataAdapter object as parameter and modifies it (creates the appropriate CRUD logic)!

I do not think that it is correct to pass in a parameter to the constructor of an object and expect to get it modified! It is not explicit, and it has no explanation to what happens! Constructors should never modify the parameters they receive. They should only set up their "this" based on the parameters.

The SqlCommandBuilder object that we created is never used from that point onward in our code! We created an object only to inject functionality into the SqlDataAdapter!

I consider that the elegant solution would be to have a static method in the SqlCommandBuilder class that operates on the parameter SqlDataAdapter.

I still can not understand the reason or the justification for this constructor in the SqlCommandBuilder class. If any of you can give me a good reason for this, I would very much appreciate it.

Filed in .net, it, thoughts 0 comments
No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
«
Next Post
»

Switch to our mobile site