簡體   English   中英

我們如何實現編寫可重用和模塊化的代碼

[英]How we can achieve writing reusable and modular code

我們如何在企業代碼中實現編寫可重用和模塊化的代碼。 入門的基礎是什么

編寫模塊化代碼是一種編程藝術。

在企業產品中,編寫可重用代碼是使您的產品長期可靠、可測試和可維護的關鍵。 模塊化和可重復使用的代碼是任何標准產品的核心。

讓我們舉個例子來了解我們如何將現有代碼轉換為更模塊化和可重用的代碼。

假設產品中存在一種方法/邏輯,它將一維正整數數組作為輸入並計算所有元素的總和。

// Method signature
// Business: Each element of array holds the amount of total transaction done by the user on each day for a year. Hence the array length is 365.(ignore leap year)
int sumYear (int [] A) {
        
        // logic
        sum of elements from index 0 to last index (364) of array A
}

該方法實際上評估了用戶在給定年份的總交易金額。 考慮到這是最初的業務需求,因此代碼是以這種方式編寫的。

現在,假設有一個新的業務需求來了,它想要評估上半年的用戶交易。 你將如何實現它? 也許再寫一個可以評估上半年的方法。 正確的。 讓我們看看該方法的樣子。

// Method signature
// Business: Each element of array holds the amount of total transaction the user has done on each day for a year. Hence the array length is 365.
int sumHalfYear (int [] A) {
        
        // logic
        sum of elements from index 0 to last index (182) of array A (ignore leap year)
}

很酷,我們已經做到了。 :) 但它可以用任何其他方式完成,或者可能是更好的方式。 讓我們看看。

我們實際上可以編寫一個更通用/可重用的方法,它可以給出給定時間段內的交易總和。 像這樣的東西

// Method signature
// Business: Each element of array holds the amount of transaction the user has done on each day for a year. Hence the array length is 365.
// startIndex: Starting index to consider for evaluation
// endIndex: Ending index to consider for evaluation
int sum (int [] A, int startIndex, int endIndex) {
        
        // logic
        sum of elements from index "startIndex" to "endIndex" of array A (ignore leap year)
}

現在我們可以為兩個現有需求調用這個可重用的方法。

// Method signature
// Business: Each element of array holds the amount of transaction the user has done on each day for a year. Hence the array length is 365.
int sumYear (int [] A) {
        
        //sum of elements from index 0 to last index (364) of array A
        return sum(A, 0, 364);

}

// Method signature
// Business: Each element of array holds the amount of transaction the user has done on each day for a year. Hence the array length is 365.
int sumHalfYear(int[] A) {
        
        //sum of elements from index 0 to last index (182) of array A (ignore leap year)
        return sum(A, 0, 182);
}

甚至任何未來的需求,比如說一月份,我們需要像這樣簡單地調用相同的方法

// Method signature
// Business: Each element of array holds the amount of transaction an user has done on each day for a year. Hence the array length is 365.
int sumJanuray (int [] A) {
        
        //sum of elements from index 0 to last index (30) of array A
        return sum(A, 0, 30);
}

為什么我們要尋找更好的方法? 可能是為了適應未來的需求並減少代碼行。

我們取得的成就:

  1. 更高的可用性
  2. 更高的可維護性
  3. 較少的代碼行
  4. 由於業務邏輯修改,未來不太容易回歸

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM