Simple and clean C # method design case: sfcui. ajaxloadpage () 2

Source: Internet
Author: User

One or two

Merge obvious code

The so-called obvious code is the code that looks the same as elsewhere.

In this example, the content displayed on the initial page of view is the same as the content refreshed in the future. The calculation and refresh operations are the same in controller.

The Controller is easy to handle, so:

        private void PrepareAssignItemsData(int sprintID)        {            var sprint = ...            var team = ...            var overTimes = ...;            var itemsTreeInSprint = ...            ViewBag.AssignItemsViewModel = ...            ViewBag.ViewModel = ...        }        public ActionResult AssignItems(int sprintID)        {            PrepareAssignItemsData(sprintID);            return View("~/Areas/SFC/Views/Items/ItemTree.cshtml");        }        public ActionResult AjaxRefreshAssignItemsLeftPad(int sprintID)        {            PrepareAssignItemsData(sprintID);            return View("~/Areas/Agile/Views/PlanningMeetings/AjaxRefreshAssignItemsLeftPad.cshtml");        }

On the cshtml page, you only need to add a function that will automatically refresh the page during page initialization, so that the <Div id = "leftpad"> can be empty and filled by refreshing the page. Code:

 

<script type = "text/javascript">    $(document).ready(function () {        refreshLeft();    });    function refreshLeft() {        $("#refreshLeft").click();    };</script><div style = "display: no1ne">    @SFCUI.Link("refresh", "/Agile/PlanningMeetings/AjaxRefreshAssignItemsLeftPad?sprintID=" + assignItemsViewModel.Sprint.ID, ajaxUpdateTargetID: "leftpad", ajaxOnSuccess: "refreshAll", id: "refreshLeft")</div><div id = "leftpad"></div>

$ (Document). Ready is an extra code that fills in the content of <Div id = "leftpad> during the first initialization.

Encapsulate redundant technical code

What is redundant technical code? Previously, the ajaxvalue series mentioned two interface encapsulation principles:

Minimum Information Principle: Method interfaces should only transmit the most necessary business information.

There are two layers:

1. Do not transmit technical data

2. Business data cannot be duplicated

 

Now, let's analyze from the business point of view what information is necessary in the function interface design. Let's use this principle to put the last section of the above cshtml code, A line of code.

1. If you want to refresh, what function should you call (generally a JS function is provided to the red box on the left. If the red box runs successfully, this JS function will be called)

2. Ajax URL used to refresh the page (the URL to which the above JS function is called to obtain the refreshed content)

3. after the refresh is successful, what operations are to be continued (another JS function, such as refreshing the content "missed document. ready "needs to be applied again-I tried the live function, but I don't know why it is invalid; or I want to refresh multiple regions in series, which is not in this example)

No (I will see some later, but for other functions ). There are a few things redundant:

1. $ (document). Ready..., because every ajaxpageload is executed, it is fixed and does not need to be passed into the interface as a parameter.

2. function refreshleft ()... {$ "# refreshleft ")...., this button is redundant and does not need to be manually clicked. It is only a step in function implementation. In other words, this button does not matter, as long as the values in ready/function/sfcui. Link (ID:...) are the same, you do not need to manually specify.

3. <Div id = "leftpad"> </div> is redundant! Since the line of code is written here, it is loadpage in the code. It doesn't matter what the ID is.

Therefore, the interface call should be:

    @SFCUI.AjaxLoadPage("/Agile/PlanningMeetings/AjaxRefreshAssignItemsLeftPad?sprintID=" + assignItemsViewModel.Sprint.ID, refreshFunction: "refreshLeft", ajaxOnSuccess: "refreshAll")

This is a helper, which will be responsible for producing the <SCRIPT> and its two functions ready, refreshleft, and <div> @ sfcui. ajax call in link </div> and the last <Div id = "leftpad">

The following is the source code of helper. Some parameters are added and the final explanation is as follows:

        public const string AJAX_LOAD_PAGE_CLASS = "ajaxloadpage";        private static Random _rand = new Random();        public static MvcHtmlString AjaxLoadPage(string pageLink, string refreshFunction = null, string ajaxOnSuccess = null, string style = null, int timeout = 0)        {            int id = _rand.Next();            string html = SFCUI.Link("refresh", "/SFC/Ajax/AjaxLoadPage?pageLink=" + HttpUtility.UrlEncode(pageLink), ajaxUpdateTargetID: id.ToString() + "Body", ajaxOnSuccess: ajaxOnSuccess, cssClass: "hide " + AJAX_LOAD_PAGE_CLASS + " ", id: id.ToString()).ToString();            TagBuilder script = new TagBuilder("script");            script.MergeAttribute("type", "text/javascript");            script.InnerHtml = "$(document).ready(function () { setTimeout(function () {  $(\"#" + id.ToString() + "\").click(); }, " + timeout + "); });";            if (refreshFunction != null)                script.InnerHtml += "function " + refreshFunction + "() { $(\"#" + id.ToString() + "\").click(); };";            html += script.ToString();            TagBuilder pageContainer = new TagBuilder("div");            pageContainer.MergeAttribute("id", id.ToString() + "Body");            pageContainer.MergeAttribute("style", style);            html += pageContainer.ToString();            return new MvcHtmlString(html);        }

1. first look at the sudden jump of int id = _ Rand. Next ()

As mentioned above, we have many "random" variables, such as the "refreshleft", which can be called anything, and the outside world does not care. However, if it is set to a constant, if two loadpages are put on the same page, the system will fight and generate an ID using a random. Why is static used? Because the random generation mechanism uses the system time during the call as the "Seed" to generate the next random number from the seed. If the call interval is "0", the same seed and the same random number will be generated. Static does not solve this problem. You can use one and sort it down.

In short, the random ID replaces the "refreshleft" variable that needs to be passed in ".

2. The tagbuilder script directly generates a script above the code, saving you from writing the script.

Why is refreshfunction null? In one scenario, refresh is not performed repeatedly.

In my project, menus are extremely complex, and the menu generation time is even longer than the page itself. But what should we do if we don't sacrifice powerful menus for performance? Submenu delay generation!

Because people appear on the page after 1 ~ The menu will not be operated within 5 seconds (it will be operated only when the page is left), so we set all the heavy sub-menus to be loaded using ajaxloadpage, and pay attention to the last parameter timeout, most of them are loaded after 1000 milliseconds. At that time, the page was displayed to the user.

In this scenario, no one will refresh the menu, so the refreshfunction parameter is not required.

3. the tagbuilder pagecontainer replaces the original <Div id = "leftpad">. Its IDs are also randomly generated, but because IDs in 1, 2, and 3 are mutually taken care, although not visible to the outside world, the internal operation is smooth.

4. There is an extra style, which is required when we load the menu.

Conclusion

Merging the obvious code is the basic skill of junior programmers and also the basic requirement of product code. It is difficult to encapsulate redundant Technical Code. However, the above mentioned principles cannot be implemented with your care.

Why is encapsulation effort required? Code in bulk has low requirements on programmers. As long as the code is tested and functions are the same, there will be no defects. Isn't it the same?

During my 16 years of it practice, I found that most of the software that was finally developed to be vulnerable to crashes was rarely plagued by a single technical problem or defect, and most of them were plagued by illness; the main problem that is plagued by hundreds of diseases is poor maintainability. The main cause of poor maintainability is code bloated and repetitive, especially repetitive and non-repetitive.

After encapsulation:

1. always use the same piece of code, which is easy to maintain.

2. It is always used repeatedly and the quality of the Code is guaranteed.

3. identify defects in one place. After modifying the code, you can avoid defects in multiple places at the same time.

4. You can easily read the code at the business level without going deep into the technical level.

5. Spending time on code encapsulation is much more interesting than repeating code.

......

Many people in the "dangerous occupations" series of previous IT careers mentioned: "I have been doing repetitive work without accumulation. Is it very dangerous? What should I do ?" In fact, everything seems to be repeated. I have been engaged in Web programming for more than a year (only 6 months of programming volume exceeds 50% of the total workload). jquery just figured out last month, however, I believe that many web programmers will not encapsulate the code for a long time, but copy and paste the code repeatedly.

In fact, there is no repetitive work, but a repetitive work mentality.

In the future, I will write a series of IT career articles on "How to improve in repetitive work.

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.