-2
\$\begingroup\$

In my method I have something like this:

returnValue = null; 
if (!string.IsNullOrEmpty(pa.Phone))
{
    if (pa.Length != 10 && member == Schema.Phone.Name)
    {
        returnValue = new stuff;
    }
}

if (!string.IsNullOrEmpty(pa.OtherPhone))
{
    if (pa.OtherPhone.Length != 10 && member == Schema.OtherPhone.Name)
    {
        returnValue = new stuff;
    }
}

if (!string.IsNullOrEmpty(pa.Fax))
{
    if (pa.Fax.Length != 10 && member == Schema.Fax.Name)
    {
        returnValue = new stuff
    }
}

// even more similar ifs...

// at the end of method: return returnValue;

How can I refactor this logic? Note that new stuff is always the same for all the ifs.

\$\endgroup\$
3
  • \$\begingroup\$ Is the first nested if supposed to be Pa.Phone.Length rather than Pa.Length? \$\endgroup\$
    – Tory
    Apr 29, 2014 at 19:28
  • 5
    \$\begingroup\$ It would be nice if you included the entire method (even if it's long), so we have actual context and don't have to guess about what pa and member might be. Also new stuff should probably be new Stuff(); ...and then we can help you come up with a more descriptive title ;) \$\endgroup\$ Apr 29, 2014 at 19:50
  • \$\begingroup\$ @Mat'sMug Ulugbek Umirov got it right with the info I had posted. \$\endgroup\$ Apr 29, 2014 at 20:32

2 Answers 2

5
\$\begingroup\$

If member is string.

Func<string, string, bool> f = (p, m) => !string.IsNullOrEmpty(p) && p.Length != 10 && member == m;
if (f(pa.Phone, Schema.Phone.Name) ||
    f(pa.OtherPhone, Schema.OtherPhone.Name) ||
    f(pa.Fax, Schema.Fax.Name))
{
    return new stuff;
}
else
{
    return null;
}
\$\endgroup\$
1
  • \$\begingroup\$ yes, member is a string. \$\endgroup\$ Apr 29, 2014 at 19:23
1
\$\begingroup\$

A little improve to the previous post ?

Func<string, string, bool> f = (p, m) => !string.IsNullOrEmpty(p) && p.Length != 10 && member == m;
Func<dynamic[], bool> inFunc = o => o.Any(k => k);

return inFunc(new []{f(pa.Phone, Schema.Phone.Name), f(pa.OtherPhone, Schema.OtherPhone.Name),f(pa.Fax, Schema.Fax.Name)}) 
            ? (object) new stuff()
            : null;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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