掌握10种方法,提高你的代码可读性!
javascript栏目介绍如何提高代码可读性的方法。
每个人都喜欢可读性高的代码,因为高可读性的代码总是能让人眼前一亮!
就好比你向周围的人说:快看,老师!周围的人可能不屑一顾:老师有什么好看的?但如果你说:快看,苍老师!那可能很多人会被你这句话所吸引。一字之差,结果截然不同。
代码可读性的魅力也是这样,高可读性的代码,让别人抑郁理解,能够大量减少后期的维护时间。今天总结了10条常用的提高代码可读性的小方法,望大家不吝赐教。
1.语义化命名
在声明变量时,尽量让自己的变量名称具有清晰的语义化,使他人一眼便能够看出这个变量的含义,在这种情况下,可以减少注释的使用。
示例:
// bad 别人看到会疑惑:这个list是什么的集合?const list = ['Teacher.Cang', 'Teacher.Bo', 'Teacher.XiaoZe'] // good 别人看到秒懂:原来是老师们的集合!const teacherList = ['Teacher.Cang', 'Teacher.Bo', 'Teacher.XiaoZe']复制代码
2.各种类型命名
对于不同类型的变量值,我们可以通过一定的方式,让别人一看看上去就知道他的值类型。
一般来说,对于boolean类型或者Array类型的值,是最好区分的。例如:boolean类型的值可以用isXXX、hasXXX、canXXX等命名;Array类型的值可以用xxxList、xxxArray等方式命名。
// badlet belongToTeacher = true;let teachers = ['Teacher.Cang', 'Teacher.Bo', 'Teacher.XiaoZe'];// goodlet isTeacher = true;let teacherList = ['Teacher.Cang', 'Teacher.Bo', 'Teacher.XiaoZe'];复制代码
3.为常量声明
我们在阅读代码时,如果你突然在代码中看到一个字符串常量或者数字常量,你可能要花一定的时间去理解它的含义。如果使用const
或者enum
等声明一下这些常量,可读性将会有效得到提升。
示例:
// bad 别人看到会很疑惑:这个36D的含义是什么if (size === '36D') { console.log('It is my favorite'); }// good 别人看到秒懂:36D是最喜欢的大小const FAVORITE_SIZE = '36D';if (size === FAVORITE_SIZE) { console.log('It is my favorite'); }复制代码
4.避免上下文依赖
在遍历时,很多人会通过value、item甚至v等命名代表遍历的变量,但是当上下文过长时,这样的命名可读性就会变得很差。我们要尽量做到使读者即使不了解事情的来龙去脉的情况下,也能迅速理解这个变量代表的含义,而不是迫使读者去记住逻辑的上下文。
const teacherList = ['Teacher.Cang', 'Teacher.Bo', 'Teacher.XiaoZe']// bad 别人看到循环的末尾处的item时需要在去上面看上下文理解item的含义teacherList.forEach(item => { // do something // do something // do ………… doSomethingWith(item); })// good 别人看到最后一眼就能明白变量的意思是老师teacherList.forEach(teacher => { // do something // do something // do ………… doSomethingWith(teacher); })复制代码
5.避免冗余命名
某些情况的变量命名,例如给对象的属性命名,直接命名该属性的含义即可,因为本身这个属性在对象中,无需再添加多余的前缀。
// badconst teacher = { teacherName: 'Teacher.Cang', teacherAge: 37, teacherSex: 'female', };console.log(person.personName)// goodconst teacher = { name: 'Teacher.Cang', age: 37, sex: 'female', };console.log(teacher.name)复制代码
6.使用参数默认值
相比短路,使用ES6的参数默认值能让人更轻易地理解未传参数时参数的赋默认值。
// bad 需要多看一步才能理解是赋默认值function getTeacherInfo(teacherName) { teacherName = teacherName || 'Teacher.Cang'; // do...}// good 一看就能看出是赋默认值function getTeacherInfo(teacherName = 'Teacher.Cang') { // do...}复制代码
7.回调函数命名
很多人命名回调函数,尤其是为页面或者DOM元素等设置事件监听的回调函数时,习惯用事件的触发条件进行命名,这样做其实可读性是比较差的,别人看到只知道你出发了这个函数,但却需要花时间去理解这个函数做了什么。
我们在命名回调函数式,应当以函数所要执行的逻辑命名,让别人清晰地理解这个回调函数所要执行的逻辑。
// bad 需要花时间去看代码理解这个回调函数是做什么的<input type="button" value="提交" onClick="handleClick" />function handleClick() { // do...}// good 一眼就能理解这个回调函数是提交表单<input type="button" value="提交" onClick="handleSubmitForm" />;function handleSubmitForm() { // do...}复制代码
8.减少函数的参数个数
一个函数如果参数的数量太多,使用的时候就难以记住每个参数的含义了,并且函数多个参数有顺序限制,我们在调用时需要去记住每个次序的参数的含义。通常情况下我们一个函数的参数个数在1-2个为佳,尽量不要超过三个。
当函数的参数比较多时,我们可以将同一类的参数使用对象进行合并,然后将合并后的对象作为参数传入,这样在调用该函数时能够很清楚地理解每个参数的含义。
// bad 调用时传的参数难以理解含义,需要记住顺序function createTeacher(name, sex, age, height, weight) { // do...} createTeacher('Teacher.Cang', 'female', 37, 155, 45);// good 调用时虽然写法略复杂了点,但各个参数含义一目了然,无需刻意记住顺序function createTeacher({name, sex, age, height, weight}) { // do...} createTeacher({ name: 'Teacher.Cang', sex: 'female', age: 37, height: 155, weight: 45})复制代码
9.函数拆分
一个函数如果代码太长,那么可读性也是比较差的,我们应该尽量保持一个函数只处理一个功能,当逻辑复杂时将函数适当拆分。
// badfunction initData() { let resTeacherList = axios.get('/teacher/list'); teacherList = resTeacherList.data; const params = { pageSize: 20, pageNum: 1, }; let resMovieList = axios.get('/movie/list', params); movieList = resMovieList.data; }// goodfunction getTeacherList() { let resTeacherList = axios.get('/teacher/list'); teacherList = resTeacherList.data; }function getMovieList() { const params = { pageSize: 20, pageNum: 1, }; let resMovieList = axios.get('/movie/list', params); movieList = resMovieList.data; }function initData() { getTeacherList(); getMovieList(); }复制代码
10.注重写注释
不写注释应该是很多开发者的一个恶习,看别人不写注释的代码也是很多开发者最讨厌的事情。
所以,无论是为了自己还是别人,都请注重编写注释。
// bad 不写注释要花大量时间理解这个函数的作用function formatNumber(num) { if (num < 1000) { return num; } else { return `${(num / 1000).toFixed(1)}k` } }// good 有了注释函数的作用和用法一目了然/** * @param num * @return num | x.xk * @example formatNumber(1000); * @description * 小于1k不转换 * 大于1k转换为x.xk */function formatNumber(num) { if (num < 1000) { return num; } else { return `${(num / 1000).toFixed(1)}k` } }复制代码
提高代码可读性的代码风格其实还有很多,以上笔者主要从变量命名、函数和注释三个方面,总结了10条比较常用的提高代码可读性的方法,希望对大家有所帮助。如有补充,欢迎评论。
相关免费学习推荐:JavaScript(视频)
The above is the detailed content of 掌握10种方法,提高你的代码可读性!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The restrict keyword is used to inform the compiler that a variable can only be accessed by a pointer, preventing undefined behavior, optimizing code and improving readability: Preventing undefined behavior when multiple pointers point to the same variable. To optimize code, the compiler uses the restrict keyword to optimize variable access. Improves code readability by indicating that variables can only be accessed by a pointer.

Templated programming improves code quality because it: Enhances readability: Encapsulates repetitive code, making it easier to understand. Improved maintainability: Just change the template to accommodate data type changes. Optimization efficiency: The compiler generates optimized code for specific data types. Promote code reuse: Create common algorithms and data structures that can be reused.

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

The sum keyword does not exist in C language, it is a normal identifier and can be used as a variable or function name. But to avoid misunderstandings, it is recommended to avoid using it for identifiers of mathematical-related codes. More descriptive names such as array_sum or calculate_sum can be used to improve code readability.

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

std:: is a namespace in C++ that contains standard library functions, classes, and objects, simplifying software development. Its specific functions include: providing data structure containers, such as vectors and sets; providing iterators for traversing containers; including various algorithms for operating data; providing input/output stream objects for processing I/O operations; providing other practical tools, Such as exception handling and memory management.

In C language, void is a keyword that indicates no return value. It is used in various scenarios, such as: a function that declares no return value: void print_message(); a function that declares no parameter: void print_message(void); a function that defines no return value: void print_message() { printf(&quot;Hello world\n&quot;); } A function that defines no parameter: void print_message(void) { printf(&quot;Hell
