Replace conditional with polymorphism on p47
authorMichael Welch <michaelgwelch@gmail.com>
Fri, 24 Feb 2012 15:16:24 +0000 (09:16 -0600)
committerMichael Welch <michaelgwelch@gmail.com>
Fri, 24 Feb 2012 15:16:24 +0000 (09:16 -0600)
RefactoringChapter1/Movie.cs
RefactoringChapter1/Price.cs

index 6183600..60c89cf 100644 (file)
@@ -50,33 +50,7 @@ namespace RefactoringChapter1
 
         public double GetCharge(int daysRented)
         {
-
-            double result = 0;
-            switch (PriceCode)
-            {
-                case Regular:
-                    result += 2;
-                    if (daysRented > 2)
-                    {
-                        result += (daysRented - 2) * 1.5;
-                    }
-                    break;
-
-                case NewRelease:
-                    result += daysRented * 3;
-                    break;
-
-                case Childrens:
-                    result += 1.5;
-                    if (daysRented > 3)
-                    {
-                        result += (daysRented - 3) * 1.5;
-                    }
-                    break;
-
-            }
-            return result;
-
+            return _price.GetCharge(daysRented);
         }
 
         public int GetFrequentRenterPoints(int daysRented)
index dd45832..b701c2e 100644 (file)
@@ -3,6 +3,8 @@
     public abstract class Price
     {
         public abstract int PriceCode { get; }
+
+        public abstract double GetCharge(int daysRented);
     }
 
     public class ChildrensPrice : Price
         {
             get { return Movie.Childrens; }
         }
+        public override double GetCharge(int daysRented)
+        {
+            double result = 1.5;
+            if (daysRented > 3)
+            {
+                result += (daysRented - 3) * 1.5;
+            }
+            return result;
+        }
     }
 
     public class NewReleasePrice : Price
         {
             get { return Movie.NewRelease; }
         }
+
+        public override double GetCharge(int daysRented)
+        {
+            return daysRented * 3;
+        }
     }
 
     public class RegularPrice : Price
         {
             get { return Movie.Regular; }
         }
+
+        public override double GetCharge(int daysRented)
+        {
+            double result = 2;
+            if (daysRented > 2)
+            {
+                result += (daysRented - 2) * 1.5;
+            }
+            return result;
+        }
     }
 }