Replacing if else statement with any design pattern or better approach

  • A+
Category:Languages

This code doesn't look clean and this if condition can grow

public int VisitMonth(int months)     {         int visit = 0;          if (months <= 1)         {             visit = 1;         }         else if (months <= 2)         {             visit = 2;         }         else if (months <= 4)         {             visit = 3;         }         else if (months <= 6)         {             visit = 4;         }         else if (months <= 9)         {             visit = 5;         }         else if (months <= 12)         {             visit = 6;         }         else if (months <= 15)         {             visit = 7;         }         else if (months <= 18)         {             visit = 8;         }         else if (months <= 24)         {             visit = 9;         }         else if (months <= 30)         {             visit = 10;         }         else if (months <= 36)         {             visit = 11;         }         else if (months <= 48)         {             visit = 12;         }         else if (months <= 60)         {             visit = 13;         }         else         {             visit = 14;         }         return visit;     } 

Is there any better solution to this problem? Sadly that function isn't linear so it's not easy to code that in a mathematical way.

 


Possibly in C# 8 (this feature is not official yet, but works in recent IDEs if you turn it on):

int months = ...; int visit = months switch {     int j when j <= 1 => 1,     int j when j <= 2 => 2,     int j when j <= 4 => 3,     int j when j <= 6 => 4,     int j when j <= 9 => 5,     // ...     _ => 42 // default }; 

You can do similar in earlier C#, since this is a method:

public int VisitMonth(int months) {     switch (months)     {         case int j when j <= 1: return 1;         case int j when j <= 2: return 2;         case int j when j <= 4: return 3;         // etc         default: return 14;     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: