Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ JavaScript object - Flexible and dangerous     - Qt shared memory interprocess communication (Programming)

- Solve the compatibility problem between Linux and Java at the source in bold font (Linux)

- Swift acquaintance of values and references, the circular reference, Agent Precautions (Programming)

- jdbc Oracle database connection string writing pluggable (Database)

- iOS persistence of data archiving NSKeyedArchiver (Programming)

- Mounting Windows shared directory system under the Linux (Linux)

- Linux asynchronous read documents by AIO (Programming)

- Empty password Linux operating system (Linux)

- Linux modify environment variables method (Linux)

- Nginx caching using the official guide (Server)

- Objective-C basic program structure (Programming)

- Source MongoDB 3.2.1 installed on CentOS6.5 (Database)

- Linux password file security issues detailed usage (Linux)

- MongoDB study notes - polymerization (Database)

- Oracle 12c In-Memory Study (Database)

- SecureCRT in Python scripting study guide (Programming)

- Smooth upgrade to OpenSSH 6.7 Procedure (Linux)

- Hadoop 2.7.1 Installation and Configuration under RedHat Linux 6.5 (Server)

- Java foundation comb: Array (Programming)

- Ubuntu install driver manager Mint Driver Manager and Device Driver Manager (Linux)

 
         
  JavaScript object - Flexible and dangerous
     
  Add Date : 2018-11-21      
         
         
         
  No kind of data structure is simpler than the object of JavaScript flexible. As a weak dynamically typed languages, JavaScript object's properties without any constraint, the result of that is, when in use so cool, what would like to add properties directly coupled with the herd, there is no limit or template class, I want to read what properties directly "point" out on the line, write it is quite simple; however, when this code runs it ......

JavaScript This flexibility of the biggest problems is no constraint. For example, a shop system has two parts, one to generate the order object, another part of the object to get orders display. Let dry naturally behind the front-end programmers to show that part of the thing, for example, to show orders inside commodity prices on the page, will fall order.product.price.sum. However, write part of the code which generates orders buddy child is not necessarily reliable, in order to have a gift that is not price, price is no field altogether, or adjust the front end order.product.price.sum, too, js code execution to which even dead , behind Han also get out. Even more frightening is that many systems now introduced a node, the front end of the separation boundary moved back part of it, this time calling order.product.price.sum on the node, too, get out the entire page.

Is not that very low in this case? Your company already provides a good estimate of the order data in the product price field there will be, even if I did not price the rear end of Big Brother will give you a pass {}. Moreover, people with the rear end of the java, strongly statically typed language, various properties already defined, Zeneng lost it? Besides the front of the line to be tested for so long, how can online out of this problem?

Now JSON is already flying between network standard data structure, even if the back-end system you are using java to write, call this tip to write the backend interface obtained or JSON. But this is JSON turn it from what? You must expect a certain kind of object it? Unbearable. Perhaps as early as the back-end brother found Java too rigid, in order to fit the flexible JSON, with a map of the early people. Moreover, even if the rear end honest with class, if your shop system is large, there are several different types of shop orders, these orders are not afraid of it comes from the same class, the field is inevitable that there are differences, you can guarantee you development team to complete the document properties you can master all like it?

Anyway, we are not so full of documents, even if sometimes a little document, the backend will be well-intentioned brother told me: the Code shall prevail!

If you want to put this on the line before missing fields bug all measured out, I think too hard on QA brothers, back-end data are not they call the shots, Paul missing on the line long after the sudden really give less Diansha.

People always do not fly, you have to think of a way from the code.

The most direct way is to carefully every step: at risk every call to a property when they are judged at the parent node exists. This judgment carefully to what extent we should try to estimate the degree of reliable data sources. Total for the previous example, an order where they would not even trade it did not, so the code could look like this:
var showPrice
if (order.product.price)
  showPrice = order.product.price

The reality is often more complex, for example, I now want to get the phone number of the order data is a product manufacturer contact information inside the first one, and I do not trust backend interface, even the order has no products can not be guaranteed, then ......
var temp, temp1, temp2, temp3, phone;
if ((temp = order.product)! = null) {
  if ((temp1 = temp.seller)! = null) {
    if ((temp2 = temp1.contact)! = null) {
      if ((temp3 = temp2.phone)! = null) {
        phone = temp3 [0];
      }
    }
  }
}

So clumsy! JS so if you want to write back and I'd rather do the backend to write Java!

I coffeescript. In fact, we are doing the project and not built on top of coffee, but I used coffee, how to use is another topic, anyway, with the coffee, this code is this:
phone = order.product? .seller? .contact? .phone? [0]

Unfortunately, I am somewhat obsessive-compulsive disorder who, when I see so many question marks will think that a bunch if compiled, I feel for the computer tired. Besides this question mark it is easy to miss, quietly and less difficult to find a question mark. Anyway, I think I will only be in front of the property may be missing a question mark.

In fact, do these judgments do nothing more than a property once the call chain missing direct return undefined. js itself does not provide this stuff, himself a package.
Object.prototype.getAttr = function (path) {
  attrLink = path.split ( '.');
  var ref = this [attrLink [0]];
  for (var i = 1; i     if (ref)
      ref = ref [attrLink [i]];
    else
      return undefined;
  }
  return ref;
}

So it would access properties like this:
order.getAttr ( 'product.seller.contact.phone.0')

So safe. But when debugging I would rather have to explain abnormal red Used tell me who in the end is not defined or is empty quiet Mimi did not want to get an undefined value. Answer is affirmative, the above code in the output log ref is empty on the line. The last question is getAttr method is not brute force method to get the properties, unlike Java, as long as the private property can only be used getter. Let alone ensure that other small partners must use this method to take property, even I might have read, read directly on the spot. Ultimately, the Object.getAttr way I never used in the actual development.

Feeling that in front of a question mark inside cofee approach is enough, if we ourselves feel this property have to have the back-end interfaces are not passed that too that Han had. But the truth is that everything is possible, this also can not blame the rear end of Big Brother, chances are that the order data is sent over from other systems or very old wonderful data.

Ye trouble? My principle is to minimize the loss as much as possible, that is, the code range Anomalies reduced to a minimum. It is up to try..catch.

Try to look at the case where the code, the total can not catch what try what. But still some laws.

Those who do not fly our own data should not be written, but from the external interface, data interfaces use this code there is definitely a certain range, at least this situation is to try some of the. It is too rough. Look at the data in the characteristics of a large number of external data is often iterative, for example, will display a list of orders on the order list will certainly be a cycle, then the cycle for internal try it, this is at most an order can not be displayed. There is no local data where there is a unified process, for example, I do use handlebars node project template, will use a lot of custom helper, the helper for most of the data into the displayed results, such as price format What. Compare Coincidentally these helper has a uniform code entry:
helpers = _.extend (
    require ( './ helper1'),
    require ( './ helper2'),
    require ( './ helper3')
)
// "_" Is the underscore or lodash

In fact, that is, the individual files helpers integrate into a large object, then:
module.exports = _.reduce (helpers, function (memo, f, k) {
    memo [k] = function () {
        try {
            return f.apply (this, arguments)
        } Catch (e) {
            console.error ( 'handlebars helper error', e)
            return ''
        }
    }
    return memo
}, {})

Before export all the helper functions are wrapped in a try ... catch in. This has a helper in the field are also missing error will cause a little something not show.

In fact, I put all the helper into one large object whose original intention was not for this, but since the files are registered every helper again looks to repeat too much, feel uncomfortable. There is not a well-known principle of code maintenance is probably saying "any duplicate code should avoid" do? This look out the benefits.

It seems to look perfect, but also not. Later, a man child wrote a helper, I did not put these helpers inside, but registered in other files go alone, and the results of data really wonderful there, really hard to detect to the tragedy staged. . .

Well, in the final analysis with various sorts of clever but useless also arrived, but not outlaw the cards. In fact, I really want to end all comrades around the data format ordained, and strictly enforced.
     
         
         
         
  More:      
 
- Java Virtual Machine Basics (Programming)
- Linux SU command security Suggestions (Linux)
- Replace font under Linux (Linux)
- Java environment to build a number of issues (Linux)
- MySQL use the integer type (Database)
- Nginx server load balancing dual-system availability (Server)
- Extended use of the swap file swap space on Linux (Linux)
- Three minutes to teach you to easily grasp the grep command regular expression (Linux)
- Ubuntu install ruby (Linux)
- Apache Tomcat integration and resin (Server)
- Forgot Linux root password (Linux)
- Switching Virtual Machine + Ubuntu graphical interface and terminal interface (Linux)
- Elementary OS Freya global menu (Linux)
- PHP file upload methods exist in the database (Programming)
- iOS GCD multithreading simple to use (Programming)
- Create the container and run the application Docker (Server)
- The practical application of Oracle synonyms + dblink (Database)
- To learn linux security (Linux)
- Linux, security encryption to transfer files between machines (Linux)
- Using PPA to install the lightweight theme software HotShots 2.1.0 under Ubuntu (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.