Want to be a good developer , In addition to the superb technical level , Elegant code is the icing on the cake .
So what kind of code is standard , What kind of code can make people see , I'm impressed with you ?
1. Robustness
1.1 Parameter problem
Parameter type judgment
When using input parameters of functions , First judge whether the type of the parameter meets the expectation ;
Parameter guarantee
A parameter is required for subsequent operations , But this parameter is not passed in , You can define a minimum data in the function ( This is the default value )
as :
function add1(a,b) { return a+b; } function add2(a, b=20) { return a + b; }
add1(10); // NaN add2(10); // 30
add1 in a=10, b=undefined,10 + undefined
obtain NaN The results of , and add2 Because to give b Default values are provided 20, When add2 When passing in the second parameter ,b Will be reassigned , Otherwise, the default value is used 20.
Top add2 It can also be written as
function add2(a,b) { b = b || 20; // b No word , Just use it 20 return a + b; }
Parameter is an instance of a constructor
use instanceof To determine whether the parameter is an instance of a particular constructor
1.2 Error prone code
In the response callback of the request, the front end always returns data processing logic according to the back end , But in case the back end returns something unexpected , It is very likely to cause code error , Available try-catch Capture error ,
2. Readability
Simple and clear , Readable code , It will not only make the collaborative development personnel understand at a glance , They can also quickly locate problems during their own maintenance ,
2.1 Semantic
Development time , You can open google translate , Use easy to understand English to give variables , Methods, etc .
2.2 Nomenclature
constant - uppercase
Common variable - Small hump ( noun )
General method - Small hump ( verb )
Class or constructor - title case
local variable - Underline (_) start
2.3 Clear structure
Avoid callback nesting , priority of use promise etc.
3. Reusability
Local level : Reduce code duplication , Logic reuse , Extract public code ;
Global level : Create a common template
4. Scalability
Distinct modules
High cohesion , Low coupling
Technology
Daily Recommendation