Thursday, June 17, 2010

Single return

Avoid multiple return statements.
C# example- Code with multiple return statement.
//should not allow empty string or null string
public bool SetName(string strName)
{

    if (strName != string.Empty && strName != null)
    {
        m_strName = strName;
        return true;
    }
    return false;

}

C# example- Code with single return statement.
//should not allow empty string or null string
public bool SetName(string strName)
{
    bool blnStatus = false;
    if (strName != string.Empty && strName != null)
    {
        m_strName = strName;
        blnStatus = true;
    }
    return blnStatus;
}

Rule: Have single return statement.

1 comment:

Unknown said...

Instead of checking for valid conditions we can check invalid conditions at the begining of the function.
Code will look simple with better readability.
public bool SetName(string strName)
{
if (strName == string.Empty || strName == null)
return false;
m_strName = strName;
return true;
}