Search code examples
c#readability

C# Code readability issue


        int scalar = creature is SpecialCreature ? (creature.IsAwesome ? 700 : 500) : (creature is NotSoNormalCreature ? 
            (creature.IsAwesome ? (creature is IGreatCreature ? 450 : 280) : 240) : 
            (creature.IsAwesome ? (creature is IGreatCreature ? 300 : 200) : 160));

how should I write that code to make it more readable?

I thought of just building the ifs, but then I thought how about making some kind of "ConditionFactory"? Would that make any sense, or is it just too intricate for such a simple task?

int scalar;

if (creature is SpecialCreature)
{
    scalar = creature.IsAwesome ? 700 : 500;
}
else if (creature is NotSoNormalCreature)
{
    if (creature.IsAwesome)
    {
        scalar = creature is IGreatCreature ? 450 : 280;
    }
    else
    {
        scalar = 240;
    }
}
else
{
    if (creature.IsAwesome)
    {
        scalar = creature is IGreatCreature ? 300 : 200;
    }
    else
    {
        scalar = 160;
    }
}

Solution

  • Not sure entirely what you're going for, but since you are using a base type inheritance chain, you might elect to do something like

    interface ICreature
    {
        bool IsAwesome { get; set; }
        int GetScalar();
    }
    
    abstract class Creature : ICreature
    {
        public bool IsAwesome { get; set; }
        public virtual int GetScalar()
        {
            return 160;
        }
    }
    
    class SpecialCreature : Creature
    {
        public override int GetScalar()
        {
            return this.IsAwesome ? 700 : 500;
        }
    }
    
    class NotSoNormalCreature : Creature
    {
        public override int GetScalar()
        {
            return this.IsAwesome ? 450 : 280;
        }
    }
    
    // more ICreatures...
    

    Which would allow you to have the creature implement its own logic for determining the scalar, and your consuming code can lose the complication of caring.

    ICreature creature = GetCreatureFromSomewhere();
    int scalar = creature.GetScalar();