Discuss the advantages and disadvantages of library and Framework Design from jQuery

Source: Internet
Author: User

JQuery is a well-known javascript framework in the industry. Its implementation and design represent the highest level in the javascript field, this article will take jQuery as an example to summarize the principles and advantages and disadvantages of library and framework design.

Solve the problem

First, let's take a look at a framework I implemented. I call this library a four-Rule operation.

function add(a,b) {    return a+b;}function mul(a,b) {    return a*b;}function minus(a,b) {    return a-b;}function div(a,b) {    return a/b;}

The API of this library is concise and elegant, and its implementation is extremely elegant. It unified the four arithmetic operations into the function form, making our development more convenient. The most powerful is that this practice enables four arithmetic operations to support functional programming, such:

function acc(a,b,f) {    var jieguo = a; //http://weibo.com/2178807082/zk1kOcMPU    for(var i = 1; i<b; i++) {        jieguo = f(jieguo,a);    }    return jieguo
}

In this way, through the acc function, we can easily implement the n operation, which is exactly the beauty of functional programming.

The purpose of this example is to tell you that a framework/Library does not need to solve any problems-as long as you use concepts, blow yourself, or cheat new users.

Next, let's take a Look at the problem solved by jQuery, a very successful framework. Let's take a Look at the first example in "Brief Look" on the jQuery homepage.

DOM Traversal and Manipulation

$( "button.continue" ).html( "Next Step..." )

Well, that's right. jQuery wants to help us solve the problem of traversing the DOM. Without jQuery, we 'd like to write a traversal function.

function traversal(node, f) {    f(node);    if(node.children.length) {        for(var i = 0; i<node.children.length;i++)            traversal(node.children[i],f);    }}traversal(document.body,function(element){    if(element.tagName=="button" && element.className.match(/continue/)) {        element.innerHTML = "Next Step...";    }})

The traversal function is really super troublesome, isn't it? It can contain 175 characters! There are also 166 characters in use. After jQuery is used, it only takes 45 characters! Amazing!

Okay, forgive me for switching the thinking mode to the "write less, do more" mode. jQuery achieves this great goal by saving the workload of programmers by one character and one character.

JQuery, which is still up to kb after compression, has helped us write less code. It's amazing! This is the key point of the Library/framework design, that is, "creating problems without any problems will solve the problem! "

Name

Naming is especially important for libraries/frameworks.

In general, your library/framework won't have any advantages if you are an orthodox programmer pursuing a name that is easy to read, easy to understand, and consistent with native.

Good databases/frameworks have several naming principles. The first principle is to have a strong sense of history.

In 1980s, because the C language supports a variable name of up to 8 bytes, smart programmers used an abbreviation to retain the pronunciation of light consonants, the vowel and part of the Voiced Consonants are omitted.

For example:

  • Button => btn
  • Text => txt
  • Search => srch
  • Fuck => fk
  • Click => clk
  • Double => db

That's right. Although English letters are omitted, good English people can still read words. However, although we do not have such requirements, we can also use this name to give new people a sense of distance and absolute shock.

There is also a historical naming method: Hungary naming.

Hungary naming uses the abbreviated type as the prefix of the variable, for example

  • ICount indicates count of int type
  • SzText indicates the text of the string type.
  • BIsNumber indicates a Boolean isNumber.
  • DRate indicates double-precision floating-point rate.

Does it look cool? It is worth mentioning that sz indicates the string ending with 0. This is the implementation method of the string in C language, and JS does not implement the string like this at all, therefore, this can greatly improve your position as a newbie, and they cannot dream of sz as a string.

In addition, js is actually a weak type language, and variables are not bound to types at all.

In addition to history, special symbols are our first choice. In javascript, $ dollar and _ underline are great choices. The masterpiece here belongs to jQuery and underscore.

The $ usage of jQuery is not original, and the pioneer is prototype. js, which makes jQuery's practice quite historical. At the same time, the dollar symbol is better than the underline, the dollar symbol also has a good implication, we write the code, it is not just a mix of food, if the code often appears dollars, it will certainly bring us a lot of wealth.

Occupying these special symbols makes other frameworks unsigned and available, jQuery and prototype. jQuery was forced to come up with noconflict when fighting JavaScript-although it was never used before, after all, it would be quite effort-consuming to change the full $ into jQuery, and most people would choose to give up a library. (What do you mean there is no need to replace it? Can we solve the problem by setting a closure on the outside? Wake up, man. How can an engineer with a $ Library at the same time use this kind of advanced stuff? is it practical ?)

But don't be sad. Although we don't have $ or _ to grab, ES5 brings us more strange and usable characters that cannot be easily entered on the keyboard. First, I would like to recommend two zero-width characters <zwnj> and <zwj>. One of these two characters is a connector and the other is a non-connector. What they do is that they are invisible, with these two characters, you can create fake $.

See the following code:

var $ = 1;

I guess you never dreamed that this variable was actually $ \ u200D (<zwj> ......

Through the combination of \ u200D and \ u200C, you can create magic code, and your users will praise your magic code!

More than that! More strange characters are waiting for you to mine!

Interface Design

Besides naming, interface design is also one of the core of the framework.

The mediocre frameworks use the "single responsibility" principle to design interfaces: whether it is a class or a function, it only does one thing and is exactly the same as what is mentioned in the name.

Noooooooooooo! This is also boring!

Let's take a look at the $ usage of jQuery! From official documents:

  • JQuery (selector [, context])
  • JQuery (element)
  • JQuery (elementArray)
  • JQuery (object)
  • JQuery (jQuery object)
  • JQuery ()
  • JQuery (html [, ownerDocument])
  • JQuery (html, attributes)
  • JQuery (callback)

That's right! This function (jQuery is) has nine kinds of overloading! In addition, the overload contains at least three unrelated usage methods! For a while, I used to ask all the interviewers who claimed they are familiar with jQuery how many usage of this function. I can answer only one of the three questions, no one answered more than five!

It can be said that $ is a god in the eyes of jQuery users! Everything you can think of can be done! In the foreseeable future, I believe jQuery will combine artificial intelligence to write the same code no matter whether you want to implement any function:

$();

How do I understand the interface design principles? That is: Add functions to previous interfaces as much as possible, add functions by adding parameters and distinguishing parameter types, no matter whether they are related or what the API name is! Oh ...... by the way, we should combine the above-mentioned naming rules. Please use a magic variable name without any meaning!

Coupling

You may often hear from programmers in the old age that the program must be "High Cohesion, low coupling ". However, this statement is extremely misleading.

Let's take a look at jQuery event binding:

var hiddenBox = $( "#banner-message" );$( "#button-container button" ).on( "click", function( event ) {  hiddenBox.show();});

What if I don't want to use a selector and only want to bind events to a DOM element? The answer is, you need to first turn it into a jQuery object.

$(document.querySelector("#button-container button")).on( "click", function( event ) {  hiddenBox.show();});

Next let's take a look at the ajax section of jQuery:

$.ajax({  url: "/api/getWeather",  data: {    zipcode: 97201  },  success: function( data ) {    $( "#weather-temp" ).html( "<strong>" + data + "</strong> degrees" );  }});

What if you only want to use the $. ajax function and do not want to use selector or other functions? The answer is simple: Just like you need to use all the functions, reference jQuery with only K on the page, and then use $. ajax.

From this example, we can see the importance of coupling for a library: coupling forces the use of features that are not very accepted by you along with popular features, users will gradually get raped and take it for granted. This is precisely the secret that jQuery can become a "fact standard.

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.