Using Regular Expressions to identify possible bugs in code

In the past few days I was moved to analyze some legacy code from a huge web application written by a company I work with. I have to write some new modules to integrate in this application; but while I was reviewing the code to ‘learn’ the style and code format used (to try to build code similar to the one already written for uniformity and ease of maintenance for the other guys I work with), I faced code like this:

...

using (DbCommand c = CurrentDatabase.GetSqlStringCommand(sql))

{

CurrentDatabase.AddInParameter(c, "UserId", DbType.String, UserName);

IDataReader dr;

List<Filiale> list = new List<Filiale>();

dr = CurrentDatabase.ExecuteReader(c);

while (dr.Read())

{

list.Add(BuildObjectFromDataRow(dr));

}

return list;

}

...

Can you see the bug here ?

The DataReader is created, used ... and never closed...that is: a big resource leak! I looked around and found some more code similar to this one.

The solution is indeed huge (60+ projects) and with many classes for the data access written in an ‘old-style’ fashion. So we need a way to easily identify the ‘critical’ sections and check the code for similar resource leaks, because we do not want to check file by file if we can avoid it. I thought of it a bit and a solution came into my mind.

The best practice is to wrap each DataReader inside a using statement to clean up resources properly, and it is already used in many code fragments of the solution, so:

Why can’t I try to use the Visual Studio ‘Find and Replace’ feature with some regular expression, looking for all the pieces of code that contains an ExecuteReader() call not wrapped inside a using statement?

So I opened my favorite Regex editor an wrote down something like this:

^(?!.*\busing\b).*ExecuteReader

It basically looks for any line that contains the ‘ExecuteReader’ string and do not contains the ‘using’ string-

I tested it with some code snippets and seemed to work, the bad news is: you can’t use this in Visual Studio..because the regex syntax is a bit different from the standard, check the VS or the MSDN help for the syntax.

You have to modify the expression like this:

^(~(.*<using>)).*ExecuteReader

Using this method you can easily identify all the code to check to fix the bug mentioned above. A similar technique can be used to identify anything you like in your code.