Chris Anderson

Chris Anderson

  • NA
  • 93
  • 9.3k

How can I prevent DRY for this method?

Jan 30 2021 12:35 PM
Having each scope almost the same like below doesn't feel right at all. I'd rather have one scope where name, age i.e. are set than having 3 for each object of cat, dog and puppy. How can this code below be improved?
 
  1. private void addAnimal_Click(object sender, EventArgs e)  
  2.         {  
  3.   
  4.             var name = inputName.Text;  
  5.             int age = int.Parse(inputAge.Text);  
  6.             var favfood = inputFavfood.Text;  
  7.             var breed = inputBreed.Text;  
  8.             var typeOfAnimal = dropDownTypeOfAnimal.Text;  
  9.   
  10.   
  11.             if (typeOfAnimal == "Cat")  
  12.             {  
  13.                 Animal cat = new Cat();  
  14.   
  15.                 cat.Name = name;  
  16.                 cat.Age = age;  
  17.                 cat.FavFood = favfood;  
  18.                 cat.Breed = breed;  
  19.                 cat.IsHungry = utility.ShuffleProbability();  
  20.                 Pets.Add(cat);  
  21.             }  
  22.             if (typeOfAnimal == "Dog")  
  23.             {  
  24.                 Animal dog = new Dog();  
  25.   
  26.                 dog.Name = name;  
  27.                 dog.Age = age;  
  28.                 dog.FavFood = favfood;  
  29.                 dog.Breed = breed;  
  30.                 dog.IsHungry = utility.ShuffleProbability();  
  31.                 Pets.Add(dog);  
  32.             }  
  33.             if (typeOfAnimal == "Puppy")  
  34.             {  
  35.                 Animal puppy = new Puppy();  
  36.   
  37.                 puppy.Name = name;  
  38.                 puppy.Age = age;  
  39.                 puppy.FavFood = favfood;  
  40.                 puppy.Breed = breed;  
  41.                 puppy.IsHungry = utility.ShuffleProbability();  
  42.                 Pets.Add(puppy);  
  43.             }            
  44.   
  45.         }  
 

Answers (4)