以順其自然的思路寫程式(Thinkvd開發日誌)
有的程式在寫之前都會很好地“研究”一番,講究一些獨特的技巧,但有時可能造成後來的維護者半天看不明白。過去這方面見過,相信也有人遇到過類似的情況。
個人覺得一般程式在不響應功能的情況下應該順其自然,適合常規思維、簡單易維護為目的。
下面以開發中的thinkvd merge items 合併不同的條目為例說明一下:
實現目的:把當前選擇的ITEM合併生成新item,需要合併的item為剛生成的新item的子item,有點拗口,以圖示例:
實現思路:
1。判斷item 數不小於2條
2。生成新的item1作為父記錄
3。遍歷itemA、B、C併成為item1的子item 2,3,4
4. 將A,B,C的資料COPY到對應的2,3,4中
5。計算出item1的時長及輸出檔案大小。
相關QT程式碼:
void AxListTreeViewEx::onMergeItem()
{
QModelIndexList indexs = selectedRows();
if (indexs.count() < 2) return;
tplStringVarMap map;
map.insert("_name", "merge item");
map.insert("_outfile", "merge_tem");
map.insert("_target", m_profileComboBox->getProfileSuffix());
QModelIndex index = addItem(map, QModelIndex());
ImListTreeItem *pItem = modelEx()->getItem(index); //item1
m_profileControl->putProfileData(pItem->getItemKey());
QString s;
double totalTime = 0;
foreach(QModelIndex idx, indexs)
{
ImListTreeItem *item = modelEx()->getItem(idx); //itemA,B,C
totalTime += item->data("_duration").toDouble();
// subItem info
map.clear();
map.insert("_name", item->data("_name"));
map.insert("_duration", item->data("_duration"));
map.insert("_target", pItem->data("_target"));
// qDebug() << leftVal << "== "<< rightVal << s;
QModelIndex subIdx = addItem(map, index); //item2,3,4
ImListTreeItem *subItem = modelEx()->getItem(subIdx);
subItem->backupMediaData(item);
}
pItem->setData("_duration", totalTime);
pItem->setData("_outsize", outputSize(pItem, m_profileControl));
}
自然地實現上面的程式碼,相信將來即使它出現了問題,維護者也不會感覺到頭痛.