HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Code Improvement: Copy Regex named capture groups to strongly typed object

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
improvementgroupscapturenamedstronglytypedcoderegexobjectcopy

Problem

This code works to copy named capture groups of a Regex to the same named properties of a strongly typed object. However, it's not pretty. Someone mentioned I should use polymorphism to at least remove the five if statements.

What should I consider when improving this code? Suggested reading?

```
// Copies named capture groups in a REGEX to the properties of an object
// if the names match
static public void CopyProperties(Regex regex, Match source, object target)
{
if (target != null && source != null && source.Success)
{
var targetType = target.GetType();
// only step through non numeric capture names
foreach (var sourceProp in regex.GetGroupNames()
.Where(p => !Regex.IsMatch(p, @"^\d+$") &&
!String.IsNullOrWhiteSpace(p)))
{
// does the target property the same as source exist?
var targetPropName = targetType.GetProperty(sourceProp);
// if the source and target exist
if (targetPropName != null &&
!String.IsNullOrWhiteSpace(source.Groups[sourceProp].Value) )
{
var targetPropSetter = targetPropName.GetSetMethod();
// created a variable for each possible type
// because I couldn't inline the Convert.ToInt32, etc.
string sourceValue = source.Groups[sourceProp].Value;
int? intValue = !Regex.IsMatch(sourceValue,
@"^\d{1,10}$")
? (int?) null
: Convert.ToInt64(sourceValue) ))
targetPropSetter.Invoke(target,
new[] { (object) intValue });
if (targetPropName.PropertyType == typeof(Nullable))
targetPropSetter.Invoke(target,
new[] { (object) longValue });
if (targetPropName.PropertyType == typeof(Nullable))
targetPropSetter.Invoke(target,

Solution

By seeing the structure of your code structure i assume that all those if staements can easily be changed by a 'switch case' - which obviuosly is a code smell. I think you need to refactor your code. For further details please visit this link

Context

StackExchange Code Review Q#6960, answer score: 2

Revisions (0)

No revisions yet.