Reduce repeated code with generics to make the code more reasonable, more elegant, and more reasonable

Source: Internet
Author: User

Reduce repeated code with generics to make the code more reasonable, more elegant, and more reasonable

In this scenario, you need to connect to an interface to obtain data.

For example, obtaining the order list

Interface request parameters (in json format ):

1 {2 // public header 3 "head": {4 "method": "getOrders", // Interface method 5 "sign": "xxxx" // signature 6 }, 7 // private body 8 "body": {9 "userId": "1", // user ID10 "numPerPage": 10, // page size 11 "pageIdx ": 1 // page number 12} 13}View Code

Interface response result (in json format ):

1 {2 "head": {3 "code": 1, // status code 4 "errMsg": "successful" // message 5}, 6 "body ": {7 "pageCount": value, 8 "pageIdx": value, 9 "orders": [10 {11 "orderNo": value, 12 "orderPrice": value, 13 "orderTime": value, 14} 15] 16 "status": value, 17 "orderStatus": value18 omitted... 19} 20}View Code

By observing Request Parameters and response results, we can find that some fields are public and most of the methods used to interact with interfaces are the same. encapsulation can also be extracted here, the unstable and error-prone code is concentrated in one place. If you connect each interface method once, there will be a lot of repeated code, and it will be very error-prone (copy code, so we can encapsulate repeated Code appropriately to reduce unnecessary redundancy and make the code structure simpler and clearer.

First, extract the common request object container BaseWhere <T>:

1 /// <summary> 2 /// public header 3 /// <para> 4 /// used for interface communication, container 5 // data access layer 6 /// </para> 7 /// </summary> 8 /// <typeparam name = "T"> </typeparam> 9 public class BaseWhere <T> where T: new () 10 {11 private headBaseWhere _ head = new headBaseWhere (); 12 13 /// <summary> 14 /// 15 public headers /// </summary> 16 public headBaseWhere head {get; set ;} 17 18 private T _ body = new T (); 19 20 /// <summary> 21 /// private body 22 /// </summary> 23 public T body {get; set ;} 24} 25 26 public class headBaseWhere27 {28 // <summary> 29 // Interface method 30 /// </summary> 31 public String method {get; set ;} 32 33 // <summary> 34 // signature 35 /// </summary> 36 public String sign {get; set ;}37}View Code

Next, extract the common response object container BaseResult <T>:

1 // <summary> 2 // return packet header parameter 3 /// <para> 4 // used for interface communication, container 5 // data access layer 6 // </para> 7 // </summary> 8 // <typeparam name = "T"> </typeparam> 9 public class BaseResult <T> where T: new () 10 {11 private headBaseResult _ head = new headBaseResult (); 12 /// <summary> 13 /// 14 public headers /// </summary> 15 public headBaseResult head {get; set ;} 16 17 private T _ body = new T (); 18 /// <summary> 19 /// private body 20 /// </summary> 21 public T body {get; set;} 22} 23 24 public class headBaseResult25 {26 // <summary> 27 // Status code 28 /// </summary> 29 public String code {get; set;} 30 31 /// <summary> 32 // message 33 // </summary> 34 public String msg {get; set;} 35}View Code

Then define the Request Entity OrdersPara in the order list and the response entity OrdersResult:

1 /// <summary> 2 // order list (Request Entity) 3 /// </summary> 4 public class OrdersPara 5 {6 public string userId {get; set;} 7 8 public int numPerPage {get; set;} 9 10 public int pageIdx {get; set ;} 11} 12 13 // <summary> 14 // order list (response entity) 15 /// </summary> 16 public class OrdersResult17 {18 private IList <Order> _ orders = new List <Order> (); 19 20 public int pageCount {get; set;} 21 public int pageIdx {get; set;} 22 public IList <Order> orders {get {return _ orders;} set {_ orders = value ;}} 23} 24 25 public class Order 26 {27 private IList <OrderDetail> _ detail = new List <OrderDetail> (); 28 29 public string orderNo {get; set ;} 30 public decimal orderPrice {get; set;} 31 public string orderTime {get; set;} 32 public int status {get; set;} 33 public int orderStatus {get; set ;} 34 public int activityID {get; set;} 35 public string inclueno {get; set;} 36}View Code

Public Request Method WebAPIHelper <T>. POST (obj ):

1 public static class WebAPIHelper <T> where T: new () 2 {3 public static BaseResult <T> Post (Object postData) 4 {5 StringBuilder strResult = new StringBuilder (); 6 7 // create HttpWebRequest request 8 HttpWebRequest request = (HttpWebRequest) HttpWebRequest. create (Settings. APIURL); 9 request. method = "POST"; 10 request. contentType = "application/x-www-form-urlencoded"; 11 // serialize the request parameter 12 String strParams = JsonConvert according to the interface requirements. serializeObject (postData); 13 UTF8Encoding encoding = new UTF8Encoding (); 14 request. contentLength = encoding. getByteCount (strParams); 15 request. credentials = CredentialCache. defaultCredentials; 16 17 try18 {19 // create byte Stream 20 using (Stream reqStream = request. getRequestStream () 21 {22 reqStream. write (encoding. getBytes (strParams), 0, encoding. getByteCount (strParams); 23} 24 // get the return information 25 using (WebResponse response = request. getResponse () 26 {27 Stream streamResult = response. getResponseStream (); 28 using (StreamReader reader = new StreamReader (streamResult) 29 {30 strResult. append (reader. readToEnd (); 31} 32} 33} 34 catch (Exception ex) 35 {36} 37 38 BaseResult <T> result = new BaseResult <T> (); 39 try40 {41 result = JsonConvert. deserializeObject <BaseResult <T> (strResult. toString (); 42} 43 catch (Exception ex) 44 {45} 46 47 if (result = null) 48 {49 result = new BaseResult <T> (); 50} 51 52 if (result. body = null) 53 {54 result. body = new T (); 55} 56 57 return result; 58} 59}View Code

Call example:

public QueryOrdersResult Get(QueryOrdersPara para){    BaseWhere<OrdersPara> where = new BaseWhere<OrdersPara>();    where.head.method = "qryOrders";    where.body.userId = para.userId;    where.body.pageIdx = para.pageIdx;    where.body.numPerPage = para.numPerPage;        BaseResult<OrdersResult> result = WebAPIHelper<OrdersResult>.Post(where);    return result.body;}

This completes the encapsulation and extraction of some repeated code. You can also add unified exception handling in the WebAPIHelper <T>. POST (obj) method, such as interface server exceptions and timeout.

If you have any mistakes, please give us more advice.

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.