Web development model-how to streamline

Source: Internet
Author: User
Introduction to Web Development

After a long time in the Web field, I found that the Web is not standardized, and different communities in different languages have their own solutions. In addition, these solutions are really not concise.

JavaGenerally, the SSH architecture is used. The m layer is hibernate, and pojo with various tattoos is used. spring is a binder that saves the trouble of passing parameters. Various dependency injections make people confused. in the C layer, a batch of parameters should be passed to the functions in the service layer .... Although it is layered, when writing code, those should be placed on the Controller layer, those placed on the service layer, those placed on the DaO layer, how should the service layer organize, write several classes, etc, there is no clear standard that is very standard and confusing.

So can the Web have a standard process like creating a car. Efficient and concise? How can we use a real object-oriented approach?

Yes. Of course. Otherwise, I won't be here!

The so-called procedural nature and object orientation are actually the ways people want to simulate the natural world to develop and understand programs. Similarly, various magical algorithms, such as Ant Colony Algorithms and neural algorithms, are the results of learning reality. Therefore, many program procedures can be used to simulate some real cases.
So what should web development simulate? Bee? Ant? Or neurons?

The answer is:Assembly Line

Well, now let's talk about theory. You only need to have an impression. I will give an example in the following project. The key to effectively using this idea to standardize and improve your development efficiency is to optimize your code organization.

Generally, for a Web request, the user inputs relevant Custom parameters, and our code is the production line. The goal is to produce customized products.

In this section, we extract several elements:

  1. Our goal is a product, right? Products are the core of our entire pipeline, and all work is centered around it. in the end, we only return a product or a package (JSON format, HTML page, etc.) to the user. Remember, these are just a conversion or a transportation format ). The custom parameters submitted by the user are a property of the product.

  2. We have many pipelines, each of which can produce only one product at a time and return it to users. If you want to serve more users at the same time, you need to add pipelines. If you want to cut costs, you can reduce the time for one pipeline to produce a product.

  3. There will be many workers on the assembly line.

  4. Each worker is responsible for only one aspect.

  5. The assembly line system sends the product to the workers in order and says, "Hey, you can start processing now ". This is the only communication between the assembly line and the workers.

  6. The worker knows all the details of the product and he knows that he needs to install the screws for the product. He doesn't need a pipeline to tell himself: "Hey, I'll give you a screw. You put the screw in that place ".

How is it associated with web development? The following six items correspond to the above six items.

  1. A Web request is to return an object (product) to the user (Hey, you may say: I return a set, but this is also an object, right ?), All work is centered around this object. in the end, we only return an object to the user, or a set (JSON format, HTML page, etc. Remember, these are just a conversion or a transportation format ). Custom parameters submitted by the user should be an attribute of this object.

  2. We have many requests, and each web thread (pipeline) can only return one result. If you want to serve more users at the same time, you need to add more threads. If you want to cut costs, you need to improve the processing capability of each thread.

  3. There are many objects (workers) in the process of processing user requests. They will customize the objects to be returned to the user based on the parameters submitted by the user.

  4. Each service object can only fulfill one of its responsibilities.

  5. The system calls a fixed method of the service object in sequence. The system does not need to pass any parameters to the service. The service knows that there is only one object to process, so it can directly obtain the object.

  6. The service knows all the details of the object to be processed. It knows which attributes of the object to be filled with and which attributes have been processed. You can use these attributes.

Once we talk about it, we make a metaphor. In fact, when a user sends data, we create a basicObjectThen, we create a pipeline object. On this object, we register many workers. Then the object for loop notifies the worker one by one, because the worker only needsObjectTherefore, the transfer of return values and parameters is completely avoided. Finally, object A is packaged and passed to the user.
The code should look like this:

'''

Product A = new product (parmsfromuser); // create a basic product thread based on user parameters. currentthread. set (a); // It should be implemented using threadlocal. Put the product in the assembly line list workerlines = new arraylist (); // create a product line workerlines. register (New workera (); // registered workerlines. register (New workerb (); // register a worker for (worker: workerlines) {worker. work (); // The product line notifies the workers that they can work .}

'''

The details of the work method in the workder may look like this:

'''

Public class workera implements worker {public void work () {product A = thread. currentthread. get (); // get the product to be processed int feature1 =. feature1; int feature2 =. feature2;. result = dosomething (feature1, feature2 );}}

'''

In general, the pipeline structure is like the above. The code is still a bit ugly, right? Look at the design specifications, and there seems to be a lot more code, you will feel really unnecessary,

Of course, these are actually done by the framework. In the actual environment, it will be better. What you really need to write is the product and worker classes (you can also write multiple worker classes depending on your business complexity ),

The system will automatically let worker process the product.

In the past two daysTag SystemOneQuery functionFor example, let's talk about how to useAssembly line principleOrganization and planning code.

In fact, I used it in a search system.Assembly line principleOrganize every action. The code is very clean.

First, several concepts are involved:

  1. Tag
  2. Tag-related articles
  3. Synonym: Each tag has a synonym tag. For example, WINXP and Windows XP are synonymous.
  4. Channel: each channel contains multiple tags, which are composed of the articles aggregated by these tags.
  5. Blocked tags: each channel contains multiple tags that are not allowed to appear.
  6. Bla bla... Of course there are other

Let's look at the input and output to the system.

Channel IDs => [tag system] => list of associated articles

Tag SystemProcess:

  1. Obtain the associated tags under the channel through channel IDs.
  2. Each incoming tag has a synonym. Find them and obtain a new tag list.
  3. Find tags not allowed for these channels
  4. Obtain and sort the relevant text list based on the data.

According to the previousAssembly line principleWhen the system just obtains the channel IDs, it should be assembled into a product. After that, the entire production line should be processing this product, and there is no connection with other things.

Assume that our product object design looks like this:

'''

/*** User: William amzhu * Date: 12-5-19 * Time: */public class contexttags {public set tags_ids; // tag list public set blocked_tags_ids; // The list of blocked tags public string type; // public set channel_ids of the aggregated document type; // only Public String [] order_fields must be aggregated for articles under a specific category; // sorting Field Public String [] order_fields_desc_asc; // public set in ascending or descending order <integer> aggregation_ids; // channel IDs, public int start = 0; // The paging parameter public int size = 15; // same as public long Total = 0; // The total number of queried results public list <map> Results = new arraylist <map> (); // The result set returned to the user // The following are various magical Methods}

'''
Channel IDS (aggregation_ids), page (START, size), and final result (results) are all included in this object. Each worker (process) can get the raw material from the object or the items processed by the former worker, and put the obtained results into the original object.

When the user sends us raw materials or custom parameters, we will build the initial product like this (the following lines of code are all the code at the controller (actioin) Layer)

'''

Contexttags = registerproduct (contexttags. Class, request); // put the product into the thread and inject the request parameters into the contexttags object. Try {servicesystem. loadandrunservice (tagsrelationshipsearchservice. class); // load the service class and run} catch (exception e) {channel. content (format (fail, serviceexceptionhandler. handle (E); return ;}

'''

The registerproduct method is used to create a product object that contains parameters sent from the user. We can see that the subsequent service does not need to explicitly pass the newly registered contexttags object, because the workers who register themselves with the service can directly get it through a static method (threadlocal implementation) required products. Basically, the entire controller layer adopts this mode. Register a product and register a service.

Let's look at what the service looks like:

'''

public class SearchService extends BaseService {    @Override    public BaseService register() {        register(new TagParser());        register(new TagRelationSearch());        return this;    }}

'''

Service is also very simple, just register the workers you need to the product online. The above is all the code at the service layer. This is what we mentioned above. All work has been done by the system,

You only need to write a product, register it, write a worker, register it, And then OK.

Of course, the real business logic lies in the workers. This code will be more. We still need to emphasize that the whole system is actually built with two objects: products and workers.

At the Controller layer, we first defined contexttags and registered them to the system. Then we will define two workers and register them with the system,

The system automatically calls the worker to process the product. What we really need to program is products and workers.

The product contexttags is more like a simple pojo class. Similar to the Model in struts2. However, I also include the results returned to the user. That is, his complete self contains raw data and result data.

Well, now we will discuss how to build a worker object, which is also a lot of code. But you already have your own mode. You just need to fill in the code.

The core function of the tag system is to retrieve associated articles from the tag list. A worker B is required here.

However, the raw materials the user gives us are channel IDs, so we need a worker to convert the channel IDS into tagged IDs. this also includes identifying synonyms for each tag and words to be blocked. So this also requires a worker.

Let's see what a looks like:

'''

Class tagparser implements worker {private contexttags = context. current (). tags (); @ overrittenpublic void work () {return this. tag_channel_expand (). tag_synonyms_expand (). tag_blocked_expand ();} private tagparser tag_channel_expand (){//. .... Map channel_group = mysqlmanager. single_query (channel_groups_ SQL); contexttags. type = getstring (channel_group, "type"); contexttags. channel_ids = hashset (getstring (channel_group, "channel_ids "). split (","); return this;} private tagparser tag_synonyms_expand (){//.... contexttags. tags_ids.addall (query (synonyms_ SQL); return this;} private tagparser tag_blocked_expand (){//. ..... Contexttags. blocked_tags_ids.addall (query (tag_blocked_ SQL, _ s_tags.type); return this ;}// there are various magical Methods}

'''

Worker A has done three things.
Tag_channel_expand ()
Obtain the expected tag IDs through channel IDs.
Tag_synonyms_expand ()
Obtain all synonyms through tag IDS
Tag_blocked_expand ();
Finally, all the tags to be shielded are obtained and filled in the product (contexttags.

This is all work of. Then, B will continue to process the product:

'''

class TagRelationSearch implements Worker{{private ContextTags contextTags =Context.current().tags();@Overittenpublic void work() {    //.….    contextTags.total = getLong(MysqlManager.single_query(count_sql), "total");    List<Map> tag_relations = MysqlManager.query(search_sql, contextTags.start, contextTags.size);    contextTags.results.addAll(tag_relations);}}

'''

B's work is very simple. According to the processing result of A, obtain the raw material, find all the required data, and fill it in the product (contexttags ).

Finally, the product line automatically packs the product as JSON data and sends it to users.

The above two classes are the business logic that you really need to care about. Fill in the obtained data such as the product. You don't need to worry about other things. The system will do other things.

Finally, when you need to return the result to the user:

'''

JSONObject result = result(contextTags.results);result.put("total",contextTags.total);channel.content(result.toString());

'''

How about it. The process is very clear.

As described above, you may not be able to connect them. Let's take another look. For any HTTP request, you only need to do two things.

1. Create a product class, for example, contexttags In the example. It contains the fields of the data to be imported and the result set fields.

2. Define a worker based on business needs. For example, tagpaser and tagrelationsearch In the example parse the tag and search the document data associated with the tag respectively.

There is actually a chain relationship between workers. First, after processing by a and then processing by B, there is no coupling between them, and there is no need to access any service layer or controller layer. You only need to fill in the product.

There is also a problem, that is, the worker finds flaws in the product. For example, if a user-defined specification is not passed or an error is passed, for example, the ID field is required, however, the user ignores it. How can this problem be solved?

In this process, the worker should handle the process through the exception mechanism terminal. This mechanism will be explained later.

Therefore, the pipeline mode is easy to standardize and define products. Other people only need to implement workers, and workers are filled with fields in the product objects. Even the same action can be completed by multiple people without any conflict.

Because the entire specification is already in the product object.

Therefore, with this step in place, it is basically 8-9. In addition, it can achieve all the advantages I mentioned earlier. Among them, workers can actually be reused. Of course, it is best for a worker to understand only one product.
I don't know what you think about this model?

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.