從一個學員的代碼看源代碼管理

前言

最近做了一個項目,其中有個日誌模塊。功能要求很是簡單,只要從文件中讀取日誌並顯示即可。但是項目是一個新手程序員做的,現在面我們來看看這個新手程序員做的內容有什麼問題。

界面

界面使用了一個二維列表,顯示時間、日誌內容和時間等信息。由於不是關注重點,且界面也能夠滿足需求,所以就不再討論。

後臺代碼

以下是最主要的讀取代碼。

private void 日誌_Load(object sender, EventArgs e)
{
	this.listView1.Items.Clear();
    this.listView1.BeginUpdate();
    StreamReader sr = new StreamReader(Common.StartFolder + "\\record.log");
    while (sr.Peek() > 0)
    {
        string x = sr.ReadLine();
        if (!x.Contains(","))
            continue;
        string[] content = x.Split(',');
        if (content.Length == 4)
        {
            ListViewItem item = new ListViewItem();
            item.Text = content[0];
            item.SubItems.Add(content[1]);
            item.SubItems.Add(content[2]);
            item.SubItems.Add(content[3]);
            listView1.Items.Add(item);
        }
    }
    sr.Close();
    this.listView1.EndUpdate();
}

從以上代碼中,我們可以看到,數據讀取、數據拆分和界面關聯完成混在了一起。這樣的代碼耦合度太高,而且沒有任何可複用的內容,同時如果界面上的順序需要修改,也會比較麻煩。

修改建議

首先,既然日誌是一個可能常用的內容,我們應該定義一個日誌類。如下所示,我們即定義了類的屬性,還定義了幾個可能用到的方法。

public class TranLog
{
	public int StartID;
	public int EndID;
	public int LogTime;
	public string Result;

	public string[] ToStrings1 ()
	{
		// 代碼略。
	}
	
	public static TranLog Parse(string s)
	{
		// 代碼略。
	}

	public static TranLog[] Load(string file)
	{
		// 代碼略
	}
}

有了以上的代碼定義,現在我們再看看客戶端的代碼,可以進行以下優化。

private void 日誌_Load(object sender, EventArgs e)
{
	listView1.Items.Clear();
	listView1.BeginUpdate();
	foreach(var log in TranLog.Load(Common.StartFolder + "\\record.log"))
		listView1.Items.Add(new ListViewItem(log.ToStrings1());
	listView1.EndUpdate();
}

通過重新編寫以後,客戶端的代碼只有以下幾行。業務邏輯也變得非常清晰,即加載和界面填充,從面極大地簡化了代碼。這樣的化簡不僅易於閱讀,同樣也易於管理。

發佈了323 篇原創文章 · 獲贊 91 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章