我一直認爲具有明確簽名和3-5行代碼的方法和函數會使代碼更清晰,但在很多情況下,我被告知我也做了許多功能/方法。顯然,在一個只有很少方法的類中導航更容易。這些人說,一種方法應該僅僅爲了可重用性而分裂。我個人認爲,當一種方法更長時間後,它會因修改而變得更長,並且它會變得越來越複雜。即使是這樣,它也不會再被測試了。我已經閱讀了這個主題,但我並沒有改變主意,但似乎我一個人就這麼想。我錯了嗎?多個單一目的方法vs很少多種目的方法
我把這個代碼從MSDN:
private void CreatePO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po=new PurchaseOrder();
// Create an address to ship and bill to.
Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString();
// Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal) 5.23;
i1.Quantity = 3;
i1.Calculate();
// Insert the item into the array.
OrderedItem [] items = {i1};
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach(OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal) 12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
}
我操縱將其改造成這樣的代碼:
private void CreatePO(string filename)
{
Serialize(GetPurchaseOrder(), filename);
}
private PurchaseOrder GetPurchaseOrder()
{
return new PurchaseOrder()
{
ShipTo = GetBillAdress(),
OrderDate = System.DateTime.Now.ToLongDateString(),
OrderedItems = GetOrderedItems(),
ShipCost = (decimal)12.51
};
}
//Will be inside of PurchaseOrder class
private decimal GetSubTotal(OrderedItem[] items)
{
return items.Sum(x => x.LineTotal);
}
private OrderedItem[] GetOrderedItems()
{
OrderedItem i1 = new OrderedItem()
{
ItemName = "Widget S",
Description = "Small widget",
UnitPrice = (decimal)5.23,
Quantity = 3,
Calculate()
};
// Insert the item into the array.
return new OrderedItem[]{ i1 };
}
private void Serialize<T>(T toSerialize, string filename)
{
using (var w = new StreamWriter(filename))
{
var s = new XmlSerializer(typeof(T));
s.Serialize(w, toSerialize);
}
}
private Adress GetBillAdress()
{
return new Address()
{
Name = "Teresa Atkinson",
Line1 = "1 Main St.",
City = "AnyTown",
State = "WA",
Zip = "00000"
};
}
也許有人說,這裏的大多數功能將只能使用一次。但是,最佳做法是什麼?這種分解代碼的方式會減慢執行嗎?並編譯彙編?除了可讀性以外,什麼是真正的優點?
目前陳述的這個問題是徵求意見。請儘量重申您的問題,使其能夠更多地涉及事實而不是意見。例如,你可以做一個問題,沿着「我有這些和這些方法的具體類,我正在考慮重新設計它的方式,因爲我期望這些*具體*的好處和缺點。 ,還有其他一些缺點。「附帶一個具體的具體代碼/設計示例,具體說明您的問題。 – Alex
我認爲這個問題更適合程序員stackexchange – Guanxi