JavaScript web front-end share common anti-patterns

  web front-end share JavaScript common anti-patterns, Preface : anti-pattern refers to the inability to design a common problem of recurring design patterns and inefficient, saying that the same mistakes. This article describes some of the common anti-patterns in JavaScript, as well as ways to avoid them.

  hardcode

  Hard-coded ( Hard-Coding) string, number, date ...... you can write all the dead people write things will be dead. This is an anti-pattern including women and children, but also the most widely used anti-pattern. Hard-coded in the most typical is probably native code (Platform-Related), which refers to the code for a particular machine or environment can properly run, could only be run on your machine, it may be only in Windows under run.

  For example, in writing npm script dead script path / Users / harttle / bin / fis3 , the reason may be to install a very difficult and may be installed in order to avoid duplication, they may simply be because it so. In any case, it makes all my colleagues come to you to ask, "Why am I here will complain." The solution is to put it in the dependency management, if there are specific version requirements can use the package-lock, if all else fails it can be regarded as external dependencies can be placed in and removed from the local configuration file version control (such as Git).

  For example, in cli tool write special folders Death / tmp, ~ / .cache, or path separators or \\ /. Such strings can be obtained by generally Node.js built-in module (or other runtime API), such as the use os.homedir, os.tmpdir, path.sep like.

  Repeat Code

  Repeat Code ( Duplication) is particularly common in business code, almost all of the original intention of maintaining the stability of the business. For example: A page needs a nice search box, and the page B, there is exactly one. Then the programmer brother faced a difficult choice (if direct copy will be slightly disturbed by the words):

  •   The B copy, want to change the way A.
  •   The B in the search box to reconstruct C, B and A of this reference code.

  Due to time constraints want to leave work early, or due to change bad B need to take responsibility (PM: Why A B lets you do a bad answer to this question is more complex, where the first skip?), After some thought decided to take the program through 2.

  At this point the whole story to be very natural and very smooth, which is probably the reason for repeated code is widely used. This story has a few points to the question:

  •   B so easy to change bad description of B does not consider reuse. Then you should not reuse code B, unless it decides to take over maintenance.
  •   B responsibility than to change bad programmer brother: whether whether the author has written B test, the tester regression testing B page?
  •   Time is running does not necessarily lead to an anti-pattern, not as a reason to convince myself. There are also short-term plan to achieve elegance.

  The solution is: extracting code B redevelopment form the search box assembly C, to use it in A page. Simultaneously to use junior partner in the future, including the authors also urge the B to C migrate unified maintenance.

  False AMD

  Modular intended to refer to the function of the software separated into separate modules, each module comprising a complete breakdown of the function. In JavaScript, it is specific to the context script cut into separate, reusable code means.

  Since the JavaScript as the original page script, there are many references to the global scope of grammar, as well as many practices based on global variables. JQuery example of $, BOM provide window, omitting var defined variables. AMD is the JavaScript community earlier modular specification. This is a gentlemen's agreement, the problem lies here. There are countless ways to write fake AMD modules:

  •   No return value. Yes, that is, to the side effects.
  •   Require the direct define. Right, it is to be executed immediately.
  •   Side effects. Modify window or other shared variables, such as static properties of other modules.
  •   Concurrency issues. Unknown dependencies easily lead to concurrency issues.

  Affect the overall side effects exactly the same global variable, drawbacks almost all global variables: execution logic is not easily understood; implicit coupling relationship; written test difficult. Below to a specific example:

  // file: login.js

  define('login', function () {

  fetch('/account/login').then(x => {

  window.login = true

  })

  })

  require(['login'])

  The AMD module and write directly in a <script> no difference, more precisely uncontrollable (requirejs implementation is asynchronous). It can not be used by other modules (for example, to achieve log in again after you log off), because it did not return any interface. Furthermore the existence of this module concurrency problems (Race Condition): Use window.login determine whether the sign in touch.

  The solution is to put it abstract modules, to control its execution by an external sign in and get results. In a modular good project, the final state of all generated entry APP, shared state between modules are drawn to the nearest common ancestor.

  define(function () {

  return fetch('/account/login')

  .then(() => true)

  .catch(e => {

  console.error(e)

  return false

  }

  })

  Notes expansion

  Notes intention is to give readers a better understanding of the intent of the code, but in practice may be just the opposite. For example, a direct life:

  // judge Baidu version of the phone more than 15

  if (navigator.userAgent.match(/Chrome:(\d+))[1] < 15) {

  // ...

  }

  Haha When you read this paragraph, I believe that the above comment has successfully consume your time. If the first time you see such comments may be incredible, but true projects are most comments this state. Because the code does not always remember to maintain maintenance notes, besides maintaining the code is usually more than one person. Sequelae of C language program than the variable named "Chang wrote the comment" is also a very bad teaching.

  A clear solution is to use logic to place comments, the example code rewritten as follows:

  if (isHttpsSupported()) {

  // function by extracting + name, to avoid adding comments

  }

  function isHttpsSupported() {

  return navigator.userAgent.match(/Chrome:(\d+))[1] < 15

  }

  Function-expansion

  "Usually" think global variables and function-expansion algorithm classes are sequelae. But complex business scenarios and algorithms really different, the former have more need to explain the concept and operation and finishing. Finishing the business logic of the most effective methods and means for extracting variable naming than (of course, also have a corresponding closure or object).

  But in the real business maintenance, remain rational is not easy. When you enter dozens of times the same file to add business logic, your function will be as long and stinking like a slut bindings:

  function submitForm() {

  var username = $('form input#username').val()

  if (username === 'harttle') {

  username = 'God'

  } else {

  username = 'Mortal'

  if ($('form input#words').val().indexOf('harttle')) {

  username = 'prophet'

  }

  }

  $('form input#username').val(username)

  $('form').submit()

  }

  这只是用来示例,十几行还远远没有达到“又臭又长”的地步。 但已经可以看到各种目的的修改让 submitForm() 的职责远不止提交一个表单。 一个可能的重构方案是这样的:

  function submitForm() {

  normalize()

  $('form').submit()

  }

  function normalize() {

  var username = parseUsername(

  $('form input#username').val(),

  $('form input#words').val()

  )

  $('form input#username').val(username)

  }

  function parseUsername(username, words)

  if (username === 'harttle') {

  return 'God'

  }

  return words.indexOf('harttle') ? 'prophet' : 'Mortal'

  }

  在重构后的版本中,我们把原始输入解析、数据归一化等操作分离到了不同的函数, 这些抽离不仅让 submitForm() 更容易理解,也让进一步扩展业务更为方便。 比如在 normalize() 方法中对 input#password 字段也进行检查, 比如新增一个 parseWords() 方法对 input#words 字段进行解析等等。

  总结

  常见的反模式还有许多,比如 == 和 != 的使用;扩展原生对象;还有 Promise 相关的 等等。

Guess you like

Origin www.cnblogs.com/gcghcxy/p/11304127.html