Optimize if -else statement Ask

I have below if-else statement, and I want to optimize it more. Is there any way to optimize it more

if(entity[attributeName] != null)
{
    if (entity.FormattedValues.Contains(attributeName) && entity[attributeName].GetType() != typeof(EntityReference))
    {
        return entity.FormattedValues[attributeName];
    }
    else
    {
        return GetDisplayObjectFromRawValue(entity[attributeName]);
    }
}
else
{
    if (entity.FormattedValues.Contains(attributeName))
    {
        return entity.FormattedValues[attributeName];
    }
    else
    {
        return GetDisplayObjectFromRawValue(entity[attributeName]);
    }
}

2 answers

  • answered 2018-11-08 05:37 Tân Nguyễn

    If I understand you mean correctly, your code can be rewritten like this:

    if(entity[attributeName] != null)
    {
        return entity.FormattedValues.Contains(attributeName) && entity[attributeName].GetType() != typeof(EntityReference)
            ? entity.FormattedValues[attributeName]
            : GetDisplayObjectFromRawValue(entity[attributeName]);
    }
    
    return entity.FormattedValues.Contains(attributeName) 
            ? entity.FormattedValues[attributeName]
            : GetDisplayObjectFromRawValue(entity[attributeName]);
    

    P/S: This way has nothing to do with: it made the code run faster or it saves memory while running or something like that. Just for readability.

  • answered 2018-11-08 05:45 John

    If it's just for length of code, you could rewrite it like so:

    if (entity.FormattedValues.Contains(attributeName) 
            && (entity[attributeName] == null || entity[attributeName].GetType() != typeof(EntityReference)))
    {
        return entity.FormattedValues[attributeName];
    }
    else
    {
        return GetDisplayObjectFromRawValue(entity[attributeName]);     
    }
    

    Or expressed as a ternary statement:

    return entity.FormattedValues.Contains(attributeName) 
                && (entity[attributeName] == null || entity[attributeName].GetType() != typeof(EntityReference))
        ? entity.FormattedValues[attributeName]
        : GetDisplayObjectFromRawValue(entity[attributeName]);
    

    I've simplified your original code down to boolean values in an example here:

    • v1 (entity[attributeName] != null),
    • v2 (entity.FormattedValues.Contains(attributeName))
    • v3 (entity[attributeName].GetType() != typeof(EntityReference))

    Note that you should generally write your code in a way that promotes legibility over brevity.