只需要使用一次的代码可以随心所欲地编写。但是,在大多数情况下,遵守最佳实践和维护干净的代码至关重要。
请记住,您的代码稍后可能会被其他开发人员甚至您自己阅读。到那时,您的代码应该是不言自明的。每个变量、函数和注释都应该精确、干净且易于理解。这种方法不仅可以简化维护工作,还可以促进开发团队内部的协作和效率。
因此,当某人(或您)回来添加或修改您的代码时,将很容易理解每一行代码的作用。否则,您的大部分时间将花在试图理解代码上。对于在您的代码库上工作的新开发人员来说,也会出现同样的问题。如果代码不干净,他们将无法理解。因此,编写干净的代码非常重要。
干净的代码基本上是指的代码
为什么清洁代码很重要?
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中文网其他相关文章!