一例串讲code review

本文通过一段简单的代码将code review中的几个常见原则进行串讲。希望读者能够从中有所启发,欢迎大家交流。

如何编写优雅的代码

编写令人印象深刻的优雅代码涉及最佳实践、创造性和对使用的语言和工具的深刻理解的结合。以下是一些技巧和示例,帮助编写出色的代码:

  1. 使用清晰和描述性的命名规范:

    • 为变量、函数和类选择能清楚描述其目的的名称。
    • 示例:使用 calculateTotalPrice 而不是 calcPrice 作为函数名称。
  2. 保持函数小而专注:

    • 每个函数应该做一件事并且做得好。
    • 示例:不要用一个大函数处理用户输入、处理数据和更新 UI,而是将其拆分为更小的函数。
  3. 采用一致的格式和风格:

    • 一致性使代码更具可读性和专业性。使用风格指南或格式化工具(如 JavaScript 的 Prettier)。
    • 示例:始终使用一致的缩进、大括号风格和命名规范。
  4. 编写 DRY(不要重复自己)代码:

    • 避免重复代码;使用函数、循环或类封装可重用的代码。
    • 示例:如果在多个地方编写类似的代码,考虑创建一个可以多次调用的函数。
  5. 深思熟虑地注释和记录:

    • 留下解释复杂逻辑背后“为什么”的评论,而不是“做了什么”。
    • 示例:不要评论“遍历数组”,而是解释在那个上下文中循环为什么是必要的。
  6. 拥抱现代语言特性:

    • 使用增强可读性和效率的编程语言的最新特性。
    • 示例:在 JavaScript 中,使用模板字面量、箭头函数和解构,以实现更简洁、可读的代码。
  7. 优先考虑代码可读性:

    • 编写代码时,应该考虑下一个阅读它的人可能对项目一无所知。
    • 示例:避免过于复杂的单行代码;有时更冗长的方法更易于阅读。
  8. 优雅地实现错误处理:

    • 预见潜在故障并以提供清晰度且不干扰用户体验的方式处理错误。
    • 示例:在 JavaScript 中使用 try/catch 块优雅地管理异常。
  9. 适当使用设计模式:

    • 熟悉常见设计模式,并在适当时使用它们。
    • 示例:对只应该有一个实例的类使用单例模式。
  10. 主动重构:

    • 定期回顾并完善代码。寻找简化和优化的机会。
    • 示例:用提前返回的保护子句替换嵌套的 if 语句,以减少嵌套。
  11. 持续更新和学习:

    • 跟上领域内的最新趋势和最佳实践。技术行业发展迅速。
    • 示例:关注博客,参加网络研讨会,并参与编码社区以保持信息更新。
  12. 优雅的错误信息和日志记录:

    • 提供有助于故障排除的有用反馈,而不是通用的错误信息。
    • 示例:在错误日志中包含具体细节,以精确定位问题,同时不暴露敏感信息。

记住,代码的优雅不仅仅是为了给别人留下印象;它是关于编写高效、可维护和易于理解的代码。这是实践和持续学习带来的艺术与科学的平衡。

用一个示例实践这些原则

现在,将用一个 JavaScript 示例展示上述原则的应用,JavaScript 常用于前端开发。

假设需要创建一个函数,基于用户的年龄过滤用户列表,并以格式化的字符串返回他们的名字。

原始代码(未应用最佳实践):

function getUsers(users) {
    var result = '';
    for (var i = 0; i < users.length; i++) {
        if (users[i].age >= 18) {
            result += users[i].name + ', ';
        }
    }
    return result;
}

修订后的代码(应用最佳实践):

  1. 清晰和描述性的命名规范:

    • getUsers 重命名为 getAdultUserNames 以提高清晰度。
  2. 小而专注的函数:

    • 将逻辑拆分为更小的函数。
  3. 一致的格式和风格:

    • 使用 ES6 特性以保持一致性和清晰度。
  4. DRY 代码:

    • 创建可重用的过滤函数。
  5. 深思熟虑的注释:

    • 添加注释以解释逻辑。
  6. 现代语言特性:

    • 利用 ES6 语法,如箭头函数、constlet 和模板字面量。
  7. 可读性:

    • 使代码易于阅读和理解。
  8. 优雅的错误处理:

    • 添加基本的输入验证错误处理。
  9. 设计模式:

    • 应在大型项目中始终考虑使用合适的设计模式。
  10. 主动重构:

    • 持续改进方法。
  11. 持续更新:

    • 使用现代 JavaScript 特性。
  12. 优雅的错误信息和日志记录:

    • 提供清晰的错误信息。

修订后的代码:

/**
 * 过滤成年用户并以格式化字符串返回其名字。
 * @param {Array} users - 用户对象数组。
 * @return {String} - 成年用户的逗号分隔名字。
 */
function getAdultUserNames(users) {
    if (!Array.isArray(users)) {
        throw new Error('无效输入:预期为用户数组');
    }

    return users
        .filter(user => user.age >= 18) // 过滤成年用户
        .map(user => user.name)          // 提取名字
        .join(', ');                     // 将名字连接成字符串
}

// 示例使用
try {
    const userList = [
        { name: 'Alice', age: 22 },
        { name: 'Bob', age: 17 },
        { name: 'Carol', age: 19 }
    ];
    console.log(getAdultUserNames(userList)); // 输出:Alice, Carol
} catch (error) {
    console.error(error.message);
}

修订后的代码中有简洁、可读、可维护的函数,并使用现代 JavaScript 最佳实践。修改后的代码展示了对语言和高效编码技巧的清晰理解。


English version: Use One Example Explaining Basic Priciples In Coding

How to Write Elegant Code

Writing elegant code that impresses others involves a combination of best practices, creativity, and a deep understanding of the language and tools being used. Here are some tips and examples to help you write code that stands out:

  1. Use Clear and Descriptive Naming Conventions:

    • Choose variable, function, and class names that clearly describe their purpose.
    • Example: Use calculateTotalPrice instead of calcPrice for a function name.
  2. Keep Functions Small and Focused:

    • Each function should do one thing and do it well.
    • Example: Instead of a large function that handles user input, processes data, and updates the UI, break it down into smaller functions.
  3. Employ Consistent Formatting and Style:

    • Consistency makes code more readable and professional. Use a style guide or formatter (like Prettier for JavaScript).
    • Example: Consistently use indentation, brace style, and naming conventions.
  4. Write DRY (Don’t Repeat Yourself) Code:

    • Avoid duplicating code; use functions, loops, or classes to encapsulate reusable code.
    • Example: If you find yourself writing similar code in multiple places, consider creating a function that can be called multiple times.
  5. Comment and Document Thoughtfully:

    • Leave comments that explain the “why” behind complex logic, not the “what.”
    • Example: Instead of commenting “Looping through array,” explain why the loop is necessary in that context.
  6. Embrace Modern Language Features:

    • Use the latest features of your programming language that enhance readability and efficiency.
    • Example: In JavaScript, use template literals, arrow functions, and destructuring for more concise and readable code.
  7. Prioritize Code Readability:

    • Write code as if the next person to read it is someone who’s completely unfamiliar with the project.
    • Example: Avoid overly complex one-liners; sometimes a more verbose approach is more readable.
  8. Implement Error Handling Gracefully:

    • Anticipate potential failures and handle errors in a way that provides clarity and doesn’t disrupt the user experience.
    • Example: Use try/catch blocks in JavaScript to manage exceptions elegantly.
  9. Use Design Patterns Appropriately:

    • Familiarize yourself with common design patterns and use them where appropriate.
    • Example: Use the Singleton pattern for a class that should only have a single instance.
  10. Refactor Proactively:

    • Regularly revisit and refine your code. Look for opportunities to simplify and optimize.
    • Example: Replace nested if-statements with guard clauses for early returns to reduce nesting.
  11. Stay Updated and Learn Continuously:

    • Keep up with the latest trends and best practices in your field. The tech industry evolves rapidly.
    • Example: Follow blogs, attend webinars, and participate in coding communities to stay informed.
  12. Elegant Error Messages and Logging:

    • Instead of generic error messages, provide helpful feedback that can aid in troubleshooting.
    • Example: Include specific details in error logs that pinpoint the issue without exposing sensitive information.

Remember, elegance in code is not just about impressing others; it’s about writing code that is efficient, maintainable, and understandable. It’s a balance of art and science that comes with practice and continuous learning.

Practice These Priciples Using Only One Sample

Now, I’ll demonstrate the application of the mentioned principles with an example in JavaScript, commonly used in front-end development.

Let’s consider a scenario where we need to create a function that filters a list of users based on their age and returns their names in a formatted string.

Original Code (Before Applying Best Practices):

function getUsers(users) {
    var result = '';
    for (var i = 0; i < users.length; i++) {
        if (users[i].age >= 18) {
            result += users[i].name + ', ';
        }
    }
    return result;
}

Revised Code (Applying Best Practices):

  1. Clear and Descriptive Naming Conventions:

    • Renaming getUsers to getAdultUserNames for clarity.
  2. Small and Focused Functions:

    • Breaking down the logic into smaller functions.
  3. Consistent Formatting and Style:

    • Using ES6 features for consistency and clarity.
  4. DRY Code:

    • Creating a reusable filter function.
  5. Thoughtful Commenting:

    • Adding comments to explain the logic.
  6. Modern Language Features:

    • Utilizing ES6 syntax like arrow functions, const, let, and template literals.
  7. Readability:

    • Making the code readable and understandable.
  8. Graceful Error Handling:

    • Adding basic error handling for input validation.
  9. Design Patterns:

    • Not applicable in this simple example, but always considered in larger projects.
  10. Proactive Refactoring:

    • Continuously refining the approach.
  11. Stay Updated:

    • Using modern JavaScript features.
  12. Elegant Error Messages and Logging:

    • Providing clear error messages.

Revised Code:

/**
 * Filter users who are adults and return their names in a formatted string.
 * @param {Array} users - Array of user objects.
 * @return {String} - Comma-separated names of adult users.
 */
function getAdultUserNames(users) {
    if (!Array.isArray(users)) {
        throw new Error('Invalid input: Expected an array of users');
    }

    return users
        .filter(user => user.age >= 18) // Filtering adult users
        .map(user => user.name)          // Extracting names
        .join(', ');                     // Joining names in a string
}

// Example usage
try {
    const userList = [
        { name: 'Alice', age: 22 },
        { name: 'Bob', age: 17 },
        { name: 'Carol', age: 19 }
    ];
    console.log(getAdultUserNames(userList)); // Output: Alice, Carol
} catch (error) {
    console.error(error.message);
}

In this revised code, we have a function that is concise, readable, and maintainable, utilizing modern JavaScript best practices. It demonstrates a clear understanding of the language and efficient coding techniques.

原文链接:https://juejin.cn/post/7327872156918071347 作者:慕仲卿

(0)
上一篇 2024年1月26日 上午11:12
下一篇 2024年1月26日 下午4:00

相关推荐

发表回复

登录后才能评论