mercredi 30 mai 2018

Designing Viewmodels and avoid if else statements in controllers and write good business logic asp.net web api using design patterns

I have a web api action method which takes below Model as parameter (Post).

 public class RequestModel
 {
    public string PartType { get; set; }
    public int Quantity { get; set; }
    public decimal UnitCost{ get; set; }
    public bool? Owner { get; set; }
    public bool? DoSplit { get; set; }
 }

The options Owner/Do Split will be choosen by the user on UI and its based on Part Type. Also based on the Owner flag there is some other business logic which needs to be executed in combination with the DoSplit and Quantity. Hence I have many permuations and combinations. Going bruteforce the logic would go this way:

int existingQty = GetInitialQuantity(model.SerialId); //returns esisting qty 
if(existingQty < model.Quantity && model.Owner)
{
  // logic here
}
else if (existingQty < model.Quantity && model.Owner == false)
{

}
else if (existingQty = model.Quantity) // no need to check for DoSplit
{
}
etc..... more if else in combincation with qty comaprison, Dosplit and owner  flag checks with null checks.

based on the different property values in the model (in combination) I need to do different actions. How to avoid if else and use a proper design patterns of C# here. Since the model is passed from javascript through a web api call to my action method how can I use OOPs here for the requestmodel and avoid branching in the controller method ?

Aucun commentaire:

Enregistrer un commentaire