How to write high quality JS function - name / comment / piece robust

  (A) function named
  
  a, what is the current front-end function naming existence
  
  from the graph that, naming and cache are two major problems in computer science.
  
  This article saying the function name, although related to the scope is narrow, but the idea is the same, can learn from the other forms.
  
  Before reading through the relevant sections of code complete variables, but also targeted to find out about some of the source code, based on my experience summary, the current function name in addition to the problems the industry standard, there are still some details of the problem, such as:
  
  differences of English words of the
  
  failure to understand multi-dimensional to enhance the accuracy of naming (how to upgrade from a multi-dimensional accuracy named)
  
  does not use aids (how to use the aids)
  
  following a concise analysis.
  
  Second, the differences in Chinese and English
  
  1, why can not be named in Chinese way of doing things?
  
  Hanyu Pinyin there is ambiguity; kanji translation aid is not enough popular, and therefore can not be named in Chinese way.
  
  2, the difficulties encountered when using English
  
  biggest difficulty lies in the proper use of grammar scene.
  
  For example, react life cycle, as follows:
  
  componentDidMount
  
  componentWillReceiveProps
  
  shouldComponentUpdate
  
  many people will have questions, Why did and will.
  
  Third, how to make English style named
  
  for example:
  
  componentDidMount hook react and so is the life cycle, but why this name?
  
  componentWillReceiveProps Why this name?
  
  The answer to the following diagram:
  
  Note that the above figure did on behalf of the simple past, will future tense representative.
  
  Then we encyclopedia general past tense and future tense, as shown.
  
  (1) General past:
  
  (2) when the future General:
  
  fancy red arrow in the figure, DID indicates past tense, refers to the time when the operation occurred, used here, the meaning of hooks projecting, once the mount successful implementation this function. will the same reason.
  
  Fourth, the results returned by the function to name
  
  this is a small features, such as shouldComponentUpdate, Why should on the front.
  
  Because the value returned by this function is a Boolean value. So we can understand that this is a question, tell us in the form of questions, here is uncertain, it is necessary to determine whether the update based on the return value.
  
  Fifth, the use of tools
  
  1, with the Google translation
  
  2, with codelf
  
  this is an artifact, to search for a variety of open source projects in the variable naming, for reference.
  
  Address: unbug.github.io/codelf/
  
  corresponds to the name of the plug-VSCODE there.
  
  6, how to avoid the ambiguity function named readability and not
  
  a function of ramda source code is as follows:
  
  var = forEachObjIndexed _curry2 (forEachObjIndexed function (Fn, obj) {
  
  var = KeyList Keys (obj);
  
  IDX = 0 var;
  
  the while (IDX <keyList.length) {
  
  var = Key KeyList [IDX];
  
  Fn (obj [Key], Key, obj);
  
  IDX + =. 1;
  
  }
  
  return obj;
  
  });
  
  Export default forEachObjIndexed;
  
  this function is called forEachObjIndexed, the code was not clear the meaning of this naming function, only from the inside source for answers from the comment function in.
  
  Function Comment below:
  
  Thus know, if the function named difficulties, can be a general introduction and description of the function of the output document to solve this problem by way of comment.
  
  Seven function named classification
  
  function naming a very common phenomenon is the function name with various prefixes, as follows:
  
  - $ xxx ()
  
  - _xxx ()
  
  This function name prefixed with a variety of looks does not look good but also awkward . The core reason is that language does not support JS private variable, leading to only use _ or $ to ensure the appropriate external **** can not see.
  
  So I distal function naming divided into two categories as follows:
  
  the first category: Prefer exposed to external access function (for example, only for internal use)
  
  The second category: exposed to external access function (the various functions of the method)
  
  and Symbol naming function is a special case of initialization, as follows:
  
  const = Symbol the ADD ( 'the Add')
  
  [The ADD] (A, b) {
  
  console.log ( 'A + b')
  
  }
  
  Eight, summary
  
  summarize best practices:
  
  learn junior high school English grammar, function named open source projects is not so difficult to understand, through grammar learning and the use of tools, the basic function name can be resolved, if they can not clearly describe the purpose of the written naming function, be sure to comment function to write good, no matter how long and more difficult to understand the function name, as long as there is a good comment that is acceptable thing.
  
  Notes (b) the function of
  
  a number of well-known style comments npm package
  
  function annotation, on the one hand to improve the readability, on the other hand can also generate online documentation.
  
  A quality function, and ultimately, the comment, but that does not mean that all functions need to comment. Full of rich living, poor finite clear, important or complex functions, you can write a good comment; simple or unimportant function, you can not write comments or write a simple note.
  
  So, the current annotation functions have what ways do?
  
  1, egg.js annotation styles
  
  can be seen from the figure entry file egg.js annotation features is simple and clean.
  
  Continue to look:
  
  This is an abstracted base class, showing the author [Yiyu He] was writing this class, its style has the following comments:
  
  The first point: annotation rule constructor expression Notes rule statement.
  
  The second point: Comment trade-offs, there are some variables can not comment, some comments that you want, do not want to have that kind of comment would all comments of thought.
  
  Look at the two funny pictures:
  
  See the arrows two pictures above are pointing to the same author [fengmk2]. His function annotation rules, the first figure is no space, the second spaces, as well as comments on this return, like a lot of people are used to direct a comment to this type Object.
  
  2, lodash.js
  
  when it comes to the comment function, you can not say lodash.js. Due to limited space, this article will not do the appropriate presentation, and all of you to follow the above way to go about.
  
  Second, by thinking of online documents generated comments
  
  Some people say comments to be very standardized, easy to others, such as using jsdoc and so on. My point is, do not need some open source web project, there is no need to use jsdoc, for the following reasons:
  
  1. cumbersome, jsdoc need to follow the rules.
  
  2. personally think, jsdoc there are invasive, document rules need to write code.
  
  If you want to write a comment instruction manual, for large projects, I recommend using apidoc, because apidoc invasion is not strong, are not required to write the rules in the code, you can put all the rules written to a file.
  
  But generally small projects, there is no need to write a separate api documentation. If it is a large open source project, you first need to consider whether it is open source's official website, you will see some online open-source project official website seems pretty cool, in fact, the world does not lack is the wheel, you can quickly make such website,
  
  let's look at how to do.
  
  Taro first look at the source code, as shown below:
  
  Here is the secret to generate a static website, do npm run docs on it. Using a docusaurus package.
  
  Can know from the figure above, the contents of the document, comes from the docs directory, which is the md file, open source projects are documented here.
  
  Of course, there are also documents directly into the corresponding codes under the corresponding directory, such as ant-design below:
  
  is directly to the document on the component directory.
  
  From here we can see, the official website of the popular open source project is how to achieve, and how to write the document.
  
  Third, my personal comments habits
  
  Here to talk about some of my own personal opinion on function or style comments (just for comments function).
  
  1 share VSCode comments about several tools
  
  Better Comments to the annotation color
  
  Document This automatically generate comments
  
  TODO Highlight highlight TODO, and you can search for all TODO
  
  Below is a presentation charts:
  
  2, write, and do not comment balance
  
  my view is not affecting readability, low complexity, to function without excessive interference of the outside world can not write a comment.
  
  3, annotation expression statement
  
  in the function, annotation expression statement can be simple point. Shown later // plus the following brief description of FIG.
  
  the Add function (A, B) {
  
  // .... SUM
  
  http://www.jintianxuesha.com/?cate=5
  
  }
  
  . 4, the TODO annotation
  
  function say (www.sanguoyoux.cn) {
  
  // the TODO: write say details
  
  the console.log ( 'say')
  
  }
  
  . 5, annotation FIXME
  
  FIX function () {
  
  // FIXME: Remove console.log method
  
  console.log ( 'fix'www.zheshengyule.com)
  
  }
  
  . 6, annotation function
  
  is generally divided into ordinary functions and constructors.
  
  (1) Common function Note:
  
  / **
  
  * the Add
  
  * Number The @param {A} - Digital
  
  * @param {Number} b - Digital
  
  * @returns {Number} result - two integers and
  
  * /
  
  function the Add (A, B) {
  
  // FIXME: to here a, b parameter determines the type of
  
  the let Result = A + B
  
  return (Result)
  
  }
  
  (2) constructor Note:
  
  class Kun {
  
  / **
  
  * @constructor
  
  * @param {Object} opt - configuration object
  
  * /
  
  constructor (www.yongshenyuL.com opt = {}) {
  
  // statements Note
  
  this.config opt =
  
  }
  
  }
  
  7, summary
  
  can be found from the code open source project, based on the basic principles of compliance comment on, annotate style varied; with a different style of annotation project are also different, but I will try to balance the comments and do not comment.
  
  Robustness (c) function (defensive programming)
  
  Below is a piece:
  
  the last sentence, the test measured so many scenes, the last bar was blown up, how is it?
  
  We can see, the core of defensive programming is:
  
  all the anomalies that may occur are taken into account, and act accordingly.
  
  And I personally think it depends on the degree of defensive significant extent. Generally speaking, it is impossible to deal with all situations, but the code is an effective way to improve the robustness of the program is defensive in nature.
  
  First, think about a project
  
  I once took over a demand to rewrite Login Register binding function of the micro-letter applets and code synchronization to other small programs (applets and other development code and assist in the transfer coder smooth transition complete version ).
  
  The project due to the large user base, a high level of risk, need to consider many scenarios, such as:
  
  whether to support the online version rollback, which is the need for front-end program version AB (online have any questions, you can quickly cut to the old Login scheme)
  
  need to have a variety of verification: captcha code, SMS verification code, ip, human, fingerprint equipment, risk control, a variety of exception handling, exception reporting and other buried point.
  
  Consider the code levels: through code optimization, shortening the total response time, improve the user experience.
  
  How to ensure a single node problem, not the entire login process.
  
  How to accomplish this reasonable demand is quite difficult.
  
  PS: the problem of how to ensure that a single node point 4, does not affect the entire login process, the end the answer.
  
  Now I am on about the robustness of the function, to talk about some of my personal views.
  
  Second, the function of several ways distal robustness
  
  1, the reference to the robustness of
  
  the ES6 + soon after, written into the reference function has been optimized and improved quality. See code below:
  
  function Print (obj = {}) {
  
  the console.log ( 'name', obj.name)
  
  the console.log ( 'Age', www.xingtuylgw.com obj.age)
  
  }
  
  Print function, the argument is obj by obj = {} to be the default parameter values parameter set, thereby improving the robustness of the argument.
  
  At the same time you will find that the default value if the parameter is {}, that will function inside obj.name is undefined, it is not enough robustness, so the following will talk about the robustness of the internal function of the expression statement.
  
  2, the robust function expression statement to
  
  continue the example:
  
  function Print (obj = {}) {
  
  the console.log ( 'name:', obj.name || 'unknown name')
  
  the console.log ( 'Age : ', obj.age ||' unknown Age ')
  
  }
  
  If this is the case, expression statements become more robust, but not enough abstraction, we put a little expression statement another way to look at decoupling the code below :
  
  function Print (obj = {}) {
  
  const {name = "name unknown",
  
  console.log ( 'name:', name
  
  console.log ( 'Age:', Age)
  
  }
  
  The above code can actually re-abstraction, such as the package into console.log log function, by calling the log (name), can be done console.log ( 'name:', name ). the function of
  
  3, two levels of exception handling functions
  
  take preventive measures, do not let an exception occurs from the beginning.
  
  anomaly if there is, how to handle exceptions occur.
  
  then how to better deal with various exceptions, to improve the robustness of the function of it, I personally have the following views.
  
  4, about the principle of derivation try / catch of
  
  js node.js runs in the runtime environment provided at the time, node .js is written in C ++ .C ++ has its own exception handling mechanism, it is also a try / catch. that js a try / catch of the underlying implementation directly through the bridge, calling the C ++ try / catch.
  
  and the C ++ try / catch has Some features, such as try / catch can only catch the exception of the current thread. this explains why the abnormal synchronization of JS try / catch could catch, and for asynchronous exception can not do anything (because asynchronous is on another thread performed).
  
  here is Derivation, do not represent the exact answer.
  
  I recommend a blog:. "C ++ in the try, catch exception handling mechanism", are interested can look
  
  5, abnormal sound processing
  
  first: If synchronous operation is possible with the exception pass throw to
  
  see in the following code:
  
  the try {
  
  Error new new throw ( 'Hello godkun, I AM AN Error')
  
  the console.log ( 'at the code is not executed after the throw')
  
  } the catch (E) {
  
  the console.log (e.message)
  
  }
  
  in a synchronous manner is first throw passing exceptions, that is to throw and throw use the transfer function of the error have the same context.
  
  If context, they did not use try / catch it, but they throw an exception, then the program will crash high probability.
  
  If nodejs, this time should be coupled with a process to capture this level of uncaughtException not caught exception. Generally it will be added to the exception handling unhandledRejection.
  
  Second method: If the operation is asynchronous
  
  three ways:
  
  the use of callback, such as the error first nodejs style.
  
  For complex cases it can be used to do the Event-based way, error event to listen for the caller object.
  
  Use promise and async / await to catch an exception.
  
  How to choose which way? Based on the following principles:
  
  a simple scenario, direct use of promise and async / await to catch an exception.
  
  Complex scenes, such as multiple errors may occur, this time the best way to use Event.
  
  Third: If there are both asynchronous operation synchronous operation
  
  The best way is to use the new syntax: async / await to combine promise and try / catch to complete the capture of the abnormal operation have both synchronous asynchronous operation.
  
  Fourth Method: abstract and packaging process exception
  
  of abnormal function processing performed abstraction and encapsulation is also a way to improve the quality of the function. How to handle exceptions abstraction and encapsulation of it? There are several ways to fix it:
  
  a first way: for nodejs, the exception processing is typically packaged into a middleware, such as those based express / exception middleware koa is, usually, to handle the exception as the last middleware middleware is loaded, the purpose is to catch errors before all the middleware that may arise.
  
  The second way: nodejs or front end, the exception handling may be packaged into modules, similar to that Event.
  
  The third embodiment: the decorator pattern, the exception handling module for decorative function, such as a layer of wrapped by a function of the current try decorator / catch.
  
  The fourth way: use functional programming in the functor (Monad) like exception handling unified package, where the Monad and try / catch in the performance are the equivalent of a container, which is a very powerful way. Monad can be extended from a lot of black & exception handling, but I recommend caution, because not everyone can understand, we must consider the overall technical capabilities of the team, of course, a person, then it is a casual hi.
  
  Reasonable handling exceptions, depending on the circumstances to determine a reasonable way to handle exceptions
  
  here recommend a blog: "Evolution Callback Promise Generator Async-Await and exception handling"
  
  Third, how to ensure that a single node problems, will not affect the entire login process
  
  For example, the login process requires four security verification, according to the usual wording, one hung up, hang it all, but this is not enough robustness, how to solve this problem.
  
  On the use of the main program chain wording promise for a way to write, before writing this:
  
  pseudo-code as follows:
  
  . The auth () the then (Getip) .then (getToken to) .then (autoLogin) .then (XXX) .catch (function () {})
  
  after robust adjustment, it can be changed to the following lines:
  
  pseudo-code as follows:
  
  . the auth () the catch (goAuthErrorHandle) .then (Getip) .catch (goIPErrorHandle) .then (function (R & lt) {})
  
  after fine-tuning code, log in directly to the robustness of the process improved a lot, even if the error after error handling can also continue to pass on to the next method.
  
  Fourth, my personal views on exception handling
  
  Personally, I think for exception handling, or according to the actual situation analysis. About the following view:
  
  to consider the maintainability of the project, team skill level
  
  I had a demand, using unusual methods of treatment, such as more abstract functor, etc., although a handful of show (seek death), resulting in subsequent changes to this demand, I have to myself.
  
  To estimate the complexity and importance of good projects in advance.
  
  For example, when doing a more important business, initially I did not think so needs exception handling details, and generally the first edition, when demand did not involve a lot of exception handling, but the subsequent demand for an iterative optimization, I found exception handling It is so much a direct result of the need to rewrite code related to exception handling.
  
  So later when the project evaluation, try to learn the importance of the project according to the pit in advance to reserve a good bit.
  
  It would be a face of the future of programming mode.

Guess you like

Origin www.cnblogs.com/qwangxiao/p/11449395.html