Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
    
Is the first nested if supposed to be Pa.Phone.Length rather than Pa.Length? –  Tory Apr 29 '14 at 19:28
5  
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 ;) –  Mat's Mug Apr 29 '14 at 19:50
    
@Mat'sMug Ulugbek Umirov got it right with the info I had posted. –  user1899082 Apr 29 '14 at 20:32

2 Answers 2

up vote 5 down vote accepted

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;
}
share|improve this answer
    
yes, member is a string. –  user1899082 Apr 29 '14 at 19:23

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;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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