我是新的編碼和我最近閱讀關於代碼重構的文章。所以我做了一個控制檯應用程序來預訂船上的房間。我認爲在我的項目中只有2個部分需要重構,如下所示。 一個是if else語句。如何使這個C#代碼很小或重構此代碼
ship1 = new Ship("Olympic Countess");
ArrayList groupA = new ArrayList();
for (int i = 0; i < 10; i++)
{
groupA.Add(new room(5000, "A" + (i + 1)));
}
ArrayList groupB = new ArrayList();
for (int i = 0; i < 10; i++)
{
groupB.Add(new room(4000, "B" + (i + 1)));
}
ArrayList groupC = new ArrayList();
for (int i = 0; i < 30; i++)
{
groupC.Add(new room(3500, "C" + (i + 1)));
}
ArrayList groupD = new ArrayList();
for (int i = 0; i < 36; i++)
{
groupD.Add(new room(3400, "D" + (i + 1)));
}
ArrayList groupE = new ArrayList();
for (int i = 0; i < 40; i++)
{
groupE.Add(new room(3300, "E" + (i + 1)));
}
ArrayList groupF = new ArrayList();
for (int i = 0; i < 30; i++)
{
groupF.Add(new room(3400, "F" + (i + 1)));
}
ArrayList groupG = new ArrayList();
for (int i = 0; i < 36; i++)
{
groupG.Add(new room(3300, "G" + (i + 1)));
}
ArrayList groupH = new ArrayList();
for (int i = 0; i < 40; i++)
{
groupH.Add(new room(3200, "H" + (i + 1)));
}
ship1.addDeck("Balcony Suite", groupA);
ship1.addDeck("Suite", groupB);
ship1.addDeck("Deck 3 - Outside Twin", groupC);
ship1.addDeck("Deck 2 - Outside Twin", groupD);
ship1.addDeck("Deck 1 - Outside Twin", groupE);
ship1.addDeck("Deck 3 - Inside Twin", groupF);
ship1.addDeck("Deck 2 - Inside Twin", groupG);
ship1.addDeck("Deck 1 - Inside Twin", groupH);
}
,另一種是,如果else語句如下
public Reservation bookPassage(String cabinclass, Customer booker, int number)
{
ArrayList cabins;
if (cabinclass.Equals("a", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Balcony Suite");
else if (cabinclass.Equals("b", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Suite");
else if (cabinclass.Equals("c", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Deck 3 - Outside Twin");
else if (cabinclass.Equals("d", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Deck 2 - Outside Twin");
else if (cabinclass.Equals("e", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Deck 1 - Outside Twin");
else if (cabinclass.Equals("f", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Deck 3 - Inside Twin");
else if (cabinclass.Equals("g", StringComparison.OrdinalIgnoreCase))
cabins = ship1.getDeck("Deck 2 - Inside Twin");
else
cabins = ship1.getDeck("Deck 1 - Inside Twin");
我不明白的是我的參數是兩條邏輯改變。 那麼當我的艙艙每次都在變化時,我怎麼能爲這個邏輯做一個單獨的方法?
你應該問這對http://codereview.stackexchange.com/ – GolfWolf 2014-08-27 08:30:03
如果你的代碼工作,你的問題可能是一個更好的˚F它用於[代碼評論](http://codereview.stackexchange.com/)。 – nvoigt 2014-08-27 08:30:10