株式会社エス・スリー・フォー

C++/C#/VB.NETによる リファクタリング – リファクタリング前(C#)

Movie.cs

// Movie.cs

namespace csharp_before {

  public class Movie {

    public enum enumPriceCode {
      CHILDRENS = 2, REGULAR = 0, NEW_RELEASE = 1
    };

    private string _title;
    private enumPriceCode _priceCode;

    public Movie(string title, enumPriceCode priceCode) {
      _title = title;
      _priceCode = priceCode;
    }

    public enumPriceCode PriceCode {
      get { return _priceCode; }
      set { _priceCode = value; }
    }

    public string Title {
      get { return _title; }
    }

  }

}

Rental.cs

// Rental.cs

namespace csharp_before {

  public class Rental {

    private Movie _movie;
    private int _daysRented;

    public Rental(Movie movie, int daysRented) {
      _movie = movie;
      _daysRented = daysRented;
    }

    public int DaysRented {
      get { return _daysRented; }
    }

    public Movie Movie {
      get { return _movie; }
    }

  }

}

Customer.cs

// Customer.cs

namespace csharp_before {

  public class Customer {

    private string _name;
    private System.Collections.ArrayList _rentals;

    public Customer(string name) {
      _rentals = new System.Collections.ArrayList();
      _name = name;
    }

    public void addRental(Rental arg) {
      _rentals.Add(arg);
    }

    public string Name {
      get { return _name; }
    }

    public string statement() {
      double totalAmount = 0;
      int frequentRenterPoints = 0;
      string result = "Rental Record for " + Name + "\n";
      foreach ( Rental each in _rentals ) {
        double thisAmount = 0;
        // 一行ごとに金額を計算
        switch ( each.Movie.PriceCode ) {
        case Movie.enumPriceCode.REGULAR :
          thisAmount += 2;
          if ( each.DaysRented > 2 )
            thisAmount += (each.DaysRented - 2) * 1.5;
          break;
        case Movie.enumPriceCode.NEW_RELEASE :
          thisAmount += each.DaysRented * 3;
          break;
        case Movie.enumPriceCode.CHILDRENS :
          thisAmount += 1.5;
          if ( each.DaysRented > 3 )
            thisAmount += (each.DaysRented - 3) * 1.5;
          break;
        }
        // レンタルポイントを加算
        frequentRenterPoints++;
        // 新作を二日以上借りた場合はボーナスポイント
        if ( (each.Movie.PriceCode == Movie.enumPriceCode.NEW_RELEASE) &&
              each.DaysRented > 1 )
          frequentRenterPoints++;
        // この貸し出しに対する数値の表示
        result += "\t" + each.Movie.Title + "\t" +
                  thisAmount.ToString() + "\n";
        totalAmount += thisAmount;
      }
      // フッタ部分の追加
      result += "Amount owed is " + totalAmount.ToString() + "\n";
      result += "You earned " + frequentRenterPoints.ToString() +
                " frequent renter points";
      return result;
    }
  }
}