views:

46

answers:

1

Could this be better? .NET 2.0 compatibility for SQL Server 2005:

public static SqlString RegexSubstring(SqlString regexpattern, 
                                       SqlString sourcetext, 
                                       SqlInt32 start_position)
{
   SqlString result = null;

   if (!regexpattern.IsNull && !sourcetext.IsNull && !start_position.IsNull)
   {
      int start_location = (int)start_position >= 0 ? (int)start_position : 0;

      Regex RegexInstance = new Regex(regexpattern.ToString());
      result = new SqlString(RegexInstance.Match(sourcetext.ToString(), 
                                                 start_location).Value);
   }

   return result;
}

This is my first attempt at writing CLR functions/etc for SQL Server - is it absolutely necessary to use SqlString/etc data types for parameters?

+1  A: 

Just running it through Refactor/Pro

gave this:

public static SqlString RegexSubstring(SqlString regexpattern,
                               SqlString sourcetext,
                               SqlInt32 start_position) {
    if (regexpattern.IsNull || sourcetext.IsNull || start_position.IsNull)
        return null;

    Regex RegexInstance = new Regex(regexpattern.ToString());

    return new SqlString(RegexInstance.Match(sourcetext.ToString(),
                                               (int)start_position).Value);
}

Note that start_location is unused, so possibly you're ignoring warnings?

Another thing is just a matter of style, but can the function be written to not have a dependency on SqtTypes? Then the code becomes:

    private static string RegexSubstring(string regexpattern, string sourcetext, int start_position) {

        if (regexpattern == null || sourcetext == null || start_position == null)
            return null;

        Regex RegexInstance = new Regex(regexpattern);
        return RegexInstance.Match(sourcetext, start_position).Value;
    }

and call it with :

new SqlString(RegexSubstring(regexpattern.ToString(), sourcetext.ToString(), start_position))
Preet Sangha
Appreciate the update - dunno what I stand to gain from abstracting so I'm not calling the ToString() within the method.
OMG Ponies
Ahh like I said its just a style thing. Sometimes for unit test isolation people like to see as few dependencies as possible.
Preet Sangha
No worries, thought you were referring to the multiple return vs singular return statements pattern/anti-pattern.
OMG Ponies