Layer-based development

Source: Internet
Author: User
Tags asp net

First, let's look at an example in which book: Now you want 1 Meters You can build a bridge on a wide Creek. If you want to build this bridge on a wider River, you need to calculate the wood materials and prices. If you want the help of others, you need to add more drawings or something to help others understand your thoughts. Now you need to build bridges on the great river. You need to have an overall plan, including various aspects, such as possible future charges and profit distribution.

Here we will talk about3Layer-based architecture is actually aimed at building bridges above the great river. 1 Meters The wide Creek may not be used at all. But now I can't take a Yangtze River Bridge as an example. So here I will use this simple stream to talk about how to build a bridge. The reason why we talk so much nonsense is to prevent some people from reading this article, "what is so troublesome .." In fact, this is not a specific example, but a layered idea. It is very important to understand this.

The following is a common example of "User Logon. This example is very simple, but the sparrow is small. From data access to business rules to the interface.

Score2If you only want to study the object-oriented idea and are familiar with the implementation, you can skip the first part.

Part 1

Create a blank solution. Then:

 "Add"-"New Project"-"Other Projects"-"enterprise-level template project"-"C #Generate blocks-Data Access (data layer, hereinafter referred toDLayer)

 "Add"-"New Project"-"Other Projects"-"enterprise-level template project"-"C #Generate blocks-Business Rules (business layer, hereinafter referred toCLayer)

 "Add"-"New Project"-"Other Projects"-"enterprise-level template project"-"C #Generate block "-"WebUser Interface (interface layer, hereinafter referred toULayer)

Right-click solution-Project dependency and setUDependent onD,C,CDependent onD.

PairUAdd referenceD,CCAdd referenceD.

 

So far, a three-tier shelf has been established. What I said above is very specific and "stupid". People who know me think I am nonsense. In fact, during this time, I strongly felt that many people actually did not understand this simple process. Although there is no objection to the creation2"Empty Projects" and1"Asp net WebApplicationProgramProject can also be used3Many people think that these "enterprise-level template Projects" are actually empty projects, which is a misunderstanding. Yes, you can see from the solution resource manager that there is nothing in the enterprise-level template project. But you can open the project file in notepad and see the difference ?? You can't see some things behind the scenes, but the system is ready. That is to say, if youCIn a class in the layer,Using System Data sqlclineit", Or useSqlconnectionObject, no errors during compilation, but some "policy warnings" are generated in the "task list" to warn youCLayers should not be placed inDSomething on the layer (although it is true for the program, but the readability and maintainability are discounted) and this function cannot be provided to you by empty projects.

We know that building a bridge requires bricks. We should first prepare bricks and then build the bridge. However, in order to explain the sequence and consistency, it is simple. We should first build a bridge and reproduce the bricks during the construction process, so that there will be no more "things not needed by the bridge ". In practice, you should prepare bricks first.

U layers are actually bridges, C the layer is a brick, d layers are raw materials (stone and sand ). This also explains why U layer references and dependencies d layer (instead of U pair C , C d ), because in addition to bricks, bridges also need stone and sand.

InUCreate a LayerLogin aspx(Insert a sentence here. I do not like to automatically generateWebform1 aspxChange itLoginOrIndexOr directly delete it. I usually keep it for testing.CodeWait until the entire system is frozen and then remove it .) Add1ItemsTextbox(Id = txt),Dropdownlist(Id = DDL),Button (ID = BTN). WhereDropdownlistUsed to select the user name,ButtonIs the submit button,TextboxUsed to enter the password.

The code that must be added is divided2Part:1,Page_loadTime pairDDL.2,BTNOfClickProcessing.

1:

Private void page_load (Object sender, system. eventargs E)

{

If (! Ispostback)

 

{

This. DDL. Sort Se = datamanager. getonecolunm ("User","UID");//Explanations1

This. DDL. databind ();

}

}

2:

Private void btn_click (Object sender, system. eventargs E)

{

String uid = This. DDL. selectedvalue;

String psw=this.txt. text;

If (psw ="")

MessageBox ("Empty Password!");

Else

{

User theuser;

Try

{

Theuser = new user (UID );//Explanations2

}

Catch (exception E)

{

MessageBox (E. Message );//Explanations2

Return;

}

If (theuser. checkpsw (psw ))//Explanations3

{

Theuser. setsessions ();

 

Response. Redirect ("........");//Login successful!

}

Else

{

MessageBox ("Incorrect password!");

}

}

}

Explanations1:DatamanagerYesDA class in the layer that provides common data operations.Getonecolunm (string table, string colunm)Method returns only one1ColumnDatatableThe value is the name of the table in the database.TableColunmColumn.

Public class datamanager

{

Public datamanager ()

{

}

Public static datatable getonecolunm (string table, string colunm)

{

//The related code is omitted here. Returns the specified column in the specified table.

}

}

In fact, this area demonstratesUDirectly bypass the LayerCLayer accessDLayer, because the structure is logically simple, and obtaining the user name is not part of the business logic in the real society (only the interface is required, because it is actually used here2ItemsTextboxThis step is not required at all)

Explanations2: DefineUserClass.UserThe class definition may be as follows:

Public class user

{

Public user (string UID)

{

If (datamanager. isin ("User","Uid ='"+ Uid +"'"))

Throw"User does not exist";

Else
// User ()Other Initialization;

}

Public bool checkpsw (string psw)

{

If (datamanager. isin ("User","Uid ='"+ Uid +"'And psw ='"+ Psw +"'"))

Return true;

Else

Return false;

}

}

Note that the user class constructor usesThrowTo throw an exception that does not exist for the user.CatchUseMessageBox (E. Message );To bring up the "user does not exist" error. This is actually to demonstrate a method for passing information between layers. Exceptions are also a means. Although there can be other methods, such as return values, reference parameters directly use a method to obtain information about whether the user exists. It is not necessary to put it in the constructor. I just did this to demonstrate the transfer process, later we will discuss the application of this method in some special cases in Layered mode to solve some problems. This class is used againDatamanagerClass static methodISIN (string table, string Str)This method is actually executed"Select * from table where Str"

ThisSQLStatement.FalseOtherwise, returnTrue. A simple method. Here we have demonstratedCLayer-to-LayerDLayer call.

By the way, becauseVs. netBy default, the project name becomesNamespace, You canNamespaceChange to "solution name" to make3Layers can be freely called. Or in the called placeUsingI like the space names of other layers. For exampleLogin. aspx. CSRequiredUsing2AndUser. CSWantUsingOne.

Explanations3: The user password is also used here.UserClassCheckpsw()This method is used again.ISIN() I won't say much here.

We noticed thatUUseMessageBox ()Method to pop up the dialog box, in fact, this method is written inPagebase. CSYesUAnother file at the layer, inheritedPageClass,LoginClass inherits it. This method is actuallyResponse. Write ("<SCRIPT> alert (\""+ MSG +"\") </SCRIPT>")Encapsulated.

So far, the login is complete, and the implementation of the example is also complete. But I only talked about "ran" and didn't talk about "why ". Let's start with "why ".

Part 2

For comparison, we use a non-object-oriented, non-hierarchicalASPTypeAspxSame Logon As comparison. SpecificASPI will not write the code, but I will log on to all of them. Let's take a look at them.2(This is unfortunate, but it often happens ):

1, The Project Manager suddenly said, "No.SqlserverChangedAccess"(Genuine charges ). Look2What happens to edges separately:3Layer (A),DatamanagerChange the connection in the class (in actual circumstances, it is very likely to actually change its base class, it does not need to change itself ),Web. configTo replace the string.ASPStyle (B).Web. configAlso, the number of changes to the connection is almost the same in this specific "Creek" example, in the "bridge" example.BIt should be slightly changed, but not much. But! Please note that when we modify the code, the main time and effort are not spent on the "change" action, it is spent on "where to change" and "looking for a place to change. On the bridge,BIt takes a lot of time to find and replace most files.AIn the data layer2Layers do not need to be modified. From this perspective, we think2Point principle:

 

A)The data layer must be able to ensure the transparency of database changes (any structural changes or type changes) to other layers. That is, how the database changes. Other layers should never be changed.1Line of code! (Web. configIs the configuration of the entire application, although physically present inULayer folder, but I prefer to think that it is independent and does not belong to any layer, so it is not counted here)

B)The smaller the data layer, the better (without this principle, we place everything on the data layer, of course, database changes have no impact on the outside-because there is almost nothing outside-but this is obviously not feasible ). As we have mentioned earlier, most of the time is spent on "Searching". If you are smaller, it is easier to find it.

2, The customer suddenly proposedB/SThe version is not good.C/S. For (B!! He has to re-do all his work (or almost all of his work), although he has a lot of code to use, however, he will have to keep using previous code in "copy-paste" for a short period of time. (A) What happened ?? If you look at it carefully, you will find that (A) To create a project"WindowsUser Interface "(like the previous one, add references and project dependencies), drag several controls to the top, and name the controlTxt,DDL,BTN, And thenClickCode andPageloadThe code is copied in the past, (actually ...) Connection1You do not need to modify any line of code !!!! Of course, this is an extreme example (WinAndWebAll haveTextbox,Dropdownlist,Button3Control, and wePagebaseMethod defined inMessageBox ()And just matchWinThe same name of the method ...) However, even with so many coincidences, we can still believe that on the bridge ,(A) Compare (B. From this point of view, we thought2Similar principles:

A)The interface layer should ensure that the content of other layers does not need to be modified for any changes to the interface (regardless of the specific exampleDDLChange to anotherTextbox, OrB/SChangeC/S)

B)The smaller the interface layer, the better (the same as above .)

3, In addition to the interface layer and data layer3Layers) the rest is the content of the logic layer. Therefore, in contrast to the previous one, we can draw a conclusion:

A)The logic layer should be modified without the impact of database and interface changes.

B)The larger the logic layer, the better.2The smaller the layer, the better ...)

With the most basic principles, we should discuss how to layer the principles:

1 , Pagebase. CS what layer should I put in? Based on the above principles, it should be placed on the C layer. But in fact, I am used to placing it on the U layer, or on another layer (layer 4 , in a location lower than the data layer) layer. Where should I put it? My first practice is at the C layer, because according to the above principle, it should be placed in C , however, after a while I got used to the "four-layer", I put it on the general underlying layer (hereinafter referred to as the B layer, this layer also contains the sqlhelper class in the d layer, this includes all the "common" classes in the 3 layer. The general meaning here is that other systems can also be used without modification, this layer usually uses the company or group name as namespace instead of the solution name, when creating a solution for a new project, you can simply add existing projects and accumulate them. In practice, it plays a major role in improving efficiency and code reuse .) However, if only the 3 layer is available, I would like to place pagebase On the U layer. This is mainly because of a recent article devoted to object-oriented analysis and design. However, I added 1 to the preceding "principles": "If a class, it only exists for some special implementation of a layer, so it must be placed in this layer ", for example, pagebase exists for the special implementation ( B/S implementation) of the U layer, for example, sqlhelper exists for the special implementation of the d layer ( sqlserver database. Therefore, they must be placed on the U layer and d layer respectively. (if this is not added, they should be placed on the C layer, because the larger the C layer, the better, in addition, the 2 classes do not need to be modified for database and interface changes-although they may be useless due to changes, they still do not need to be modified)

2, OldjackyI once talked with you about one question:DataGridCan be deleted, but if only the last record is left, this delete operation is not allowed! The deletion should be placed inCLayer orDLayer orULayer? I think we should consider the following from another perspective:

A)This kind of "not allowed" is "not allowed by Business Rules" (for example, the data in the table indicates the current employee in the store, and the deletion indicates that the employee leaves the store-may take the goods or something, add indicates that the employee is returned. When there is only one clerk at the counter, it is clear that he cannot leave for delivery.) in this case, the "delete prohibited" operation should be generated inCLayer.

B)This kind of "not allowed" is "not allowed by the Program Implementation" (for example, when it is null, it will cause other places suchTostring ()Method to generate "the object reference is not set to the instance of the object ......" Or the subjective desire of the program designer or project manager to "disallow" the program to reduce the workload or simplify the program ). At this time, this "delete prohibited" can be placed inULayer (for exampleTostring) OrDLayer (for example, violation of database constraints)

3, Careful users may find that in the preceding logon example, users can obtain a total3The pop-up errors are "Empty Password", "Password error", and "user does not exist ".2InU"The user does not exist" is inCLayer (I am referring to this string) or start to talk about bridge construction, I used the "xistream bridge" here to explain the "Great River Bridge", so I intentionally turned a useless circle here, just like how many years it would take to compute the wooden board on the creek, in fact, it does not make any sense to the creek. It is only added to explain the Needs of the bridge. After all, the bridge needs such consideration. I assume that "the user does not have a prompt to pop up" is a business logic requirement, the "prompt is not required if no password is entered" is not required by the business rules (for example, a blank password can be allowed in the actual business, but the project manager does not agree that the password is required) in this login example, there is actually no problem at all, but in large projects, if this is not required by business rules, it should not be placed at the business layer. If it is a business rule, it must be placed at the business layer. It facilitates the connection between the business model and the real entity, and also facilitates the business logic to better express the characteristics of the real entity.

So far, I once again summarized our final principles:

1, If a class exists only for some special implementation of a layer, it must be placed in this layer.

 

2, The data layer should be as small as possible while ensuring that database changes are invisible to other layers.

3, The interface layer should be as small as possible without affecting the business logic layer.

4, If a class is not required by business rules, it should not be placed at the business layer, and vice versa.

5, The logical layer should be as big as possible without affecting the database or interface.

Above5Point if a conflict occurs, when finding a balance point, the previous one is higher than the later one. For example1And3Rules are more likely to be used in the case of conflicts.1.

Part 2 ends

One thing should be the scope of "programming code habits" and "Object-Oriented". However, there is some relationship with layering, so let's also talk about it. "If your code is translated into Chinese and necessary punctuation marks are added, other people who do not understand the program may still feel confused, so you may not be able to score well ". For exampleBTNOfClick:

{

The string username is the value selected from the drop-down list;

The string password is the input box value;

If the password is empty

Dialog Box (empty password !);

Otherwise

{

User;

Try

{

This user is a new user (User Name );

}

Capture (error)

{

Dialog Box (error message );

 Return;

}

If this user checks the password)

{

This user sets the status;

Response relocation ("...");

}

Otherwise

{

Dialog Box (incorrect password)

}

}

It is better for people who do not understand the code to understand what it is.

Finally,OldjackyOfDataGridThe example "delete" is displayed inDLayer, but not allowed.COrUIfUNothing to say.C, So this kind of "not allowed" is a reasonable implementation method inCThis problem occurs in the layer.Throw. WhenULayerCatchTo thisThrowThe delete operation is prohibited.2When there is a reason for the ban at the same time, you can see the source of the ban from the code at a glance. Similar to the previous2.

 Note: This article is reprinted

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.