Search code examples
c#blazormudblazor

Alternative to adding new fields in Model


I have my model class like below

public class MyModel
{
   public string Id { get; set; } = string.Empty;
   public string Name { get; set; } = string.Empty;
   public int Age{ get; set; }
   public string AgeDisplay { get; set; } = string.Empty;    
}

You can see i have added one unncessary property called AgeDisplay Somewhere in code i change AgeDisplay based on condition like

if (Age > 18)
   AgeDisplay = "Adult";
else
   AgeDisplay = "Child";

I bind AgeDisplay to my mudtable. I feel its wrong way to add extra property to model. What is other alternative?


Solution

  • This is an example of Primitive Obsession. Age is not an integer. Int.MinimumValue is not a valid age.

    You can create a value type Age and then encapsulate all the necessary logic within Age.

    Here's an example that also demonstrates some basic validation:

        public readonly record struct Age
        {
            public int Value { get; private init; }
    
            public bool IsAdult => this.Value > 18;
    
        public string TypeString => this.Value switch
            {
                < 1 => "Baby",
                < 12 => "Child",
                < 20 => "Teenager",
                < 65 => "Adult",
                _ => "Pensioner"
            };
    
            public Age(int value)
            {
                if (value < 0)
                    throw new Exception("Age Can't be less that 0");
    
                this.Value = value;
            }
        }
    
    
        public class MyModel
        {
            public string Id { get; set; } = string.Empty;
            public string Name { get; set; } = string.Empty;
            public Age Age { get; set; }
            public string AgeDisplay { get; set; } = string.Empty;
        }
    
        MyModel _model = new() { Age = new(27) };
    

    A second quick and dirty way is to create an extension class:

    public static class AgeExtensions
    {
        public static string AgeType(this int value)
            => value > 18 ? "Adult" : "Child";
    }
    

    Which you can then use like this:

    var value = 20;
    var type = value.AgeType();