只需要使用一次的程式碼可以隨心所欲地寫。但是,在大多數情況下,遵守最佳實踐和維護乾淨的程式碼至關重要。
請記住,您的程式碼可能會稍後被其他開發人員甚至您自己閱讀。到那時,您的程式碼應該是不言自明的。每個變數、函數和註釋都應該精確、乾淨且易於理解。這種方法不僅可以簡化維護工作,還可以促進開發團隊內部的協作和效率。
因此,當某人(或您)回來添加或修改您的程式碼時,將很容易理解每一行程式碼的作用。否則,您的大部分時間將花在試圖理解程式碼上。對於在您的程式碼庫上工作的新開發人員來說,也會出現相同的問題。如果程式碼不乾淨,他們將無法理解。因此,編寫乾淨的程式碼非常重要。
乾淨的程式碼基本上是指的程式碼
為什麼清潔代碼很重要?
1。可讀性和可維護性: 當程式碼寫得好、有良好的註解並遵循最佳實踐時,它很容易閱讀和理解。一旦出現問題或錯誤,您就知道在哪裡可以找到它。
2。調試: 乾淨的程式碼設計清晰、簡單,可以更輕鬆地定位和理解程式碼庫的特定部分。清晰的結構、有意義的變數名稱和定義明確的函數使識別和解決問題變得更加容易。
3。提高品質和可靠性: 乾淨的程式碼遵循特定語言的最佳實踐,並優先考慮結構良好的程式碼。它增加了品質並提高了可靠性。因此它消除了由於錯誤和非結構化程式碼而可能出現的錯誤。
現在我們了解了為什麼乾淨的程式碼至關重要,讓我們深入研究一些最佳實踐和原則來幫助您編寫乾淨的程式碼。
讓我們詳細看看。
1。避免硬編碼數字
我們可以使用常數並將該值分配給它,而不是直接使用值。因此,將來如果我們需要更新該值,我們只需在一個位置更新它。
範例
function getDate() { const date = new Date(); return "Today's date: " + date; } function getFormattedDate() { const date = new Date().toLocaleString(); return "Today's date: " + date; }在此程式碼中,在某些時候發生了變化,需要將「今天的日期:」改為「日期:」。可以透過將該字串分配給一個變數來改進這一點。
改進的程式碼:
const todaysDateLabel = "Today's date: "; function getDate() { const date = new Date(); return todaysDateLabel + date; } function getFormattedDate() { const date = new Date().toLocaleString(); return todaysDateLabel + date; }在上面的程式碼中,在需要時更改日期字串變得很容易。它提高了可維護性。
2。使用有意義且具描述性的名稱
我們可以使用更具描述性的名稱,而不是到處使用通用變數名稱,這是不言自明的。變數名本身應該定義它的使用。
命名法則
範例
// Calculate the area of a rectangle function calc(w, h) { return w * h; } const w = 5; const h = 10; const a = calc(w, h); console.log(`Area: ${a}`);這裡的程式碼是正確的,但程式碼中有一些含糊之處。讓我們看看使用描述性名稱的程式碼。
改良的程式碼
// Calculate the area of a rectangle function calculateRectangleArea(width, height) { return width * height; } const rectangleWidth = 5; const rectangleHeight = 10; const area = calculateRectangleArea(rectangleWidth, rectangleHeight); console.log(`Area of the rectangle: ${area}`);這裡每個變數名稱都是不言自明的。因此,很容易理解程式碼並提高程式碼品質。
3。僅在需要的地方使用註釋
你不需要到處寫評論。只寫在需要的地方,寫得簡短易懂。太多的註解會導致混亂和混亂的程式碼庫。
評論規則
Example
// Function to get the square of a number function square(n) { // Multiply the number by itself var result = n * n; // Calculate square // Return the result return result; // Done } var num = 4; // Number to square var squared = square(num); // Call function // Output the result console.log(squared); // Print squared number
Here we can see comments are used to define steps which be easily understand by reading the code. This comments are unnecessary and making code cluttered. Let's see correct use of comments.
Improved code
/** * Returns the square of a number. * @param {number} n - The number to be squared. * @return {number} The square of the input number. */ function square(n) { return n * n; } var num = 4; var squared = square(num); // Get the square of num console.log(squared); // Output the result
In above example comments are used only where it is needed. This is good practice to make your code clean.
4. Write Functions That Do Only One Thing
When you write functions, don't add too many responsibilities to them. Follow the Single Responsibility Principle (SRP). This makes the function easier to understand and simplifies writing unit tests for it.
Functions rules
Example
async function fetchDataAndProcess(url) { // Fetches data from an API and processes it in the same function try { const response = await fetch(url); const data = await response.json(); // Process data (e.g., filter items with value greater than 10) const processedData = data.filter(item => item.value > 10); console.log(processedData); } catch (error) { console.error('Error:', error); } } // Usage const apiUrl = 'https://api.example.com/data'; fetchDataAndProcess(apiUrl);
In the above example, we can see a function that fetches data using an API and processes it. This can be done by another function. Currently, the data processing function is very small, but in a production-level project, data processing can be very complex. At that time, it is not a good practice to keep this in the same function. This will make your code complex and hard to understand in one go.
Let's see the clean version of this.
Improved code
async function fetchData(url) { // Fetches data from an API try { const response = await fetch(url); return await response.json(); } catch (error) { console.error('Error:', error); throw error; } } function processData(data) { // Processes the fetched data (e.g., filter items with value greater than 10) return data.filter(item => item.value > 10); } // Usage const apiUrl = 'https://api.example.com/data'; fetchData(apiUrl) .then(data => { const processedData = processData(data); console.log(processedData); }) .catch(error => { console.error('Error:', error); });
In the this example, the responsibilities are separated: the fetchData function handles the API call, and the processData function handles data processing. This makes the code easier to understand, maintain, and test.
5. Avoid Code Duplication (Follow DRY Principle - Don't Repeat Your Self)
To enhance code maintainability and cleanliness, strive to create reusable functions or reuse existing code whenever possible. For instance, if you are fetching data from an API to display on a page, you would write a function that retrieves the data and passes it to a renderer for UI display. If the same data needs to be shown on another page, instead of writing the same function again, you should move the function to a utility file. This allows you to import and use the function in both instances, promoting reusability and consistency across your codebase.
Other General Rules for writing Clean Code
Implement this Practices and Principles from today to write Clean Code.
以上是什麼是乾淨的程式碼以及為什麼它很重要的詳細內容。更多資訊請關注PHP中文網其他相關文章!