How do I construct my JavaScript file?

Source: Internet
Author: User
Tags case statement coding standards event listener

Objective

See the English technical documents, fast cry. He was to be read with tears in his mouth.
Original how I Structure My JavaScript File

Content

A lot of people are asking me how to write my javascript--. Okay, this is a lie, no one asked me, but if they did, I would like to point out this article. After working with PHP for years, after reading clean code (and other books), I used my code style for years. Yes, PHP, don't knock it, it has a great community and great coding standards. Of course, I've been writing with people for years to follow different company styles.

The structure does not depend on the JS module, but I now prefer to write only the JS module, so I will use these modules.

Structure, summarized as follows:


Entrance

At the top of the file is the import. It makes sense that they are taller than anything else. The order of importation is irrelevant unless you use some hooks (such as Babel hooks), so I prefer to choose:

    1. Local module-something local to the node.

    2. Library Modules-Lodash, Knex, and more.

    3. Local libraries-such as: /db.

    4. Local files-like./helper or similar.

Keeping my modules in order makes it easier for me to see what I'm importing and what I'm actually using. When I started writing code, I also tended to write dependencies in this way.

I tend not to care about alphabetical sorting (except for breaking the import), and I don't see a point of it.

Local module
I tend to place the local module on top and maintain a clear organization with this theme:


If I'm in the browser, obviously skip this step.

Library Module

I try to import only what I need from the library, but once again, I'm grouping them into a topic.


I also noticed that if I was performing a default import (for example. I tend to put it at the top of my library module and reduce the corrupted imports. Not necessary, but I like the visual effect of it.

Local/internal Libraries

In a local library, I mean a locally shared module, such as DB. Set the JS file connected to the bookshelf. Or, in my work, we have several libraries dealing with the numbers and calculations used in our products.


Local files
Finally, I import local files, which are usually in the same folder as the files I am working on or a directory (up to). For example, I wrote a reducer for Redux and put it in a separate folder. In this folder, I have also reserved an assistant file, usually named [Reducer name]helpers.js:

Constants

After importing all the dependencies, I usually do some upfront work that will be used in the rest of the module. For example, I extracted the Knex from the Bookshelf instance. Or I can set a value constant.


Using a very good amount usually means that I rely on some type of singleton. I try to avoid using them, but sometimes it is necessary because there is no easy way to do it, or it doesn't matter (like a one-time command line script).
Exports

After I have basically set all the module-level dependencies: whether they are constant values or import libraries, I try to group my exports to the top of the file. Basically, this is the adhesive that I use as a module to achieve the ultimate purpose of the module.

In the case of Redux, I might export a single reducer, then decompose the work and invoke the related logic. In the case of EXPRESSJS, I may export all the routes here, while the actual routing logic is below.


I want to say that this is not the only part of my export function.

I feel that the way the module system works makes it a little difficult to use the boundaries between the most exposed APIs and the exported functions in the test.

For example, in the example above, I never wanted to use calculatesomething outside of a module. I'm not entirely sure how the OOP language handles testing private functions, but this is a similar problem.
Core Logic

This looks strange, but the core logic is the most important to me. I fully understand that when people flip the export and core logic, it works for me for a lot of reasons.

When I open a file, the top-level function tells me what will happen in the abstract step. I like it so much. I can see the effect of the document at a glance. I've done a lot of CSV operations and inserted them into the DB, and the top-level function is always an easy-to-understand process that has a similar flow: fetchcsv aggregatedata insertdata terminate script.

The core logic always includes top-to-bottom egress. In the inline example, we have something like this:


Note that readcsv is not. It sounds normal, I should put it in a helper file, and then import it into it. Besides, you can see my exit, not the dilemma. I don't want to provide aggregated data outside the module, but I still want to test it.

Beyond that, I tend to put the "meatier" function above, and the following function is smaller. If I have a module-specific utility function, a function I use in multiple places, but only in modules, I'll put them at the bottom. Basically, my command is: complexity + use.

So the order is:

    1. Core logic functions-functions used by the top-level export.

    2. simpler/smaller functions--functions used by the core logic functions.

    3. Utility functions--small functions used in multiple places around the module (but not exported)

Core-logic functions
The core logic function is like the "sub-glue" of the function I exported. Depending on the complexity of the module, these may or may not exist. Decomposition of functionality is not required, but if a module is large enough, the core logic function is like a step in the main function.

If you are writing a reaction or an angle, these your components will be the exit functions I mentioned above. However, the core logic functions will be implementations of various listeners or data processors. With Express, these will be your specific route. In a redux reducer, these will be a separate reducer that is far enough on the chain, without a switch/case statement.

If you are at an angle, it is completely fair to organize these functions in the class instead of the entire file.


Simpler/smaller functions

These functions are usually intermediate steps between the core logic and the Pure utility program. You might use them, or they might just be a tad more complex than utility functions. I may delete this category and say "Write your features to reduce complexity or workload".

Not mentioned here. Perhaps the Onhandleinput event listener requires some logic to process the $event data, so if it is pure, you can remove it from the class, and if not, you can keep it in the class:


Utility functions

Finally, the utility function. I tend to organize the tools closest to my use of them. In the same file, or the same folder (if necessary), the same module, and so on. Every time I use the extension from a file to the root of a project or its own NPM module, I move the function out of one level.

In my opinion, the utility function should always be a pure method, which means that it should not access the variable outside its scope, and should only rely on the data passed to it, and does not require any form of side effects. Unless you use utility functions to access the API or access the database. Because these are considered side effects, I think they are the only exceptions.


Anything else?
Of course! I think everyone has their own unique way of writing. The structure described above is very effective in the process of writing a lot of code every day for many years. Eventually, many subtle differences began to emerge, and I found myself writing code faster, liking it better, and easier to debug and test.

Before I finish this article, I would like to share with you some of the encodings that I've gotten used to, which are less related to the structure of the document and more prone to using small preferences when writing actual code.

Early returns

When I found the early payback, it was a moment. Why would you encapsulate a lot of code in an else statement when you can return early?

My rule of thumb is that if the earlier return condition was less than the rest of the code, I would write the earlier return, but if not, I would reverse the code so that the smaller block of code would always return in advance.

The early returns were excellent on the switch, and I was a big fan of redux.

Semicolon Block

Although I no longer use it (no more beautiful support), I always use a semicolon to terminate the function link, on a separate line, one indent to the left of the indentation of the chain. This creates a neat block of code that is not just hanging there.

Of course, this means I also like to use semicolons instead.


Or better written, it might look like this:

Summarize

The use of Youdao online translation, if there is not the right place also hope that the big guy pointed out.

How do I construct my JavaScript file?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.