首页  >  文章  >  web前端  >  什么是干净的代码以及为什么它很重要

什么是干净的代码以及为什么它很重要

WBOY
WBOY原创
2024-07-28 07:01:22967浏览

What is Clean Code and Why it is important

只需要使用一次的代码可以随心所欲地编写。但是,在大多数情况下,遵守最佳实践和维护干净的代码至关重要。

请记住,您的代码稍后可能会被其他开发人员甚至您自己阅读。到那时,您的代码应该是不言自明的。每个变量、函数和注释都应该精确、干净且易于理解。这种方法不仅可以简化维护工作,还可以促进开发团队内部的协作和效率。

因此,当某人(或您)回来添加或修改您的代码时,将很容易理解每​​一行代码的作用。否则,您的大部分时间将花在试图理解代码上。对于在您的代码库上工作的新开发人员来说,也会出现同样的问题。如果代码不干净,他们将无法理解。因此,编写干净的代码非常重要。

什么是干净代码?

干净的代码基本上是指的代码

    简单易懂
  1. 易于调试
  2. 易于维护
  3. 评论写得很好,简短易懂
  4. 没有重复(冗余)代码并遵循 KISS 规则(保持简单,愚蠢!)
为了编写干净的代码,开发人员必须保持代码的一致性,并且开发人员需要遵循特定语言的最佳实践。

为什么清洁代码很重要?

当团队遵循简洁代码原则时,代码库变得更易于阅读和导航。这有助于开发人员快速理解代码并开始贡献。以下是为什么干净的代码很重要的一些原因。

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。使用有意义且具有描述性的名称 我们可以使用更具描述性的名称,而不是到处使用通用变量名称,这是不言自明的。变量名本身应该定义它的使用。

命名规则

    选择描述性且明确的名称。
  1. 进行有意义的区分。
  2. 使用可发音的名称。
  3. 使用可搜索的名称。
  4. 用命名常量替换幻数。
  5. 避免编码。不要附加前缀或类型信息。

示例

// 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。仅在需要的地方使用注释 你不需要到处写评论。只写在需要的地方,并且写得简短易懂。太多的注释会导致混乱和混乱的代码库。

评论规则

  1. Always try to explain yourself in code.
  2. Don't be redundant.
  3. Don't add obvious noise.
  4. Don't use closing brace comments.
  5. Don't comment out code. Just remove.
  6. Use as explanation of intent.
  7. Use as clarification of code.
  8. Use as warning of consequences.

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

  1. Keep it Small.
  2. Do one thing.
  3. Use descriptive names.
  4. Prefer fewer arguments.
  5. Split method into several independent methods that can be called from the client.

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

  • Follow standard conventions(For JavaScript Camel Case).
  • Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
  • Boy scout rule. Leave the campground cleaner than you found it.
  • Always find root cause. Always look for the root cause of a problem.
  • Write code which is easy to understand

Implement this Practices and Principles from today to write Clean Code.

以上是什么是干净的代码以及为什么它很重要的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn