工作中遇到的“坏味道的代码”

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/csu_passer/article/details/84995673

Redundant

今天写项目的时候虽然IDE没有提示项目有重复代码,但是需要向后台get请求很多数据,很自然的,噼里啪啦根据需求写出来了下面这样的代码。

/**
 * Get nearby stores based on latitude and longitude
 * @param lat
 * @param lnt
 * @param callback
 */
function getNearbyStores(lat,lnt,callback){
  fetch(GET.NearbyStores +`?lnt= ${lnt}&lat=${lat}`).then(res => {
    if (res.ok) {
      res.json().then(result=>{
        if(typeof callback==='function') callback(result.data);
      })
    }
  }).catch(res => {
    console.log(res);
  })
}

/**
 * 
 * @param storeId
 * @param callback
 */
function getNotice(storeId,callback){
  fetch(GET.Notice +storeId).then(res => {
    if (res.ok) {
      res.json().then(result=>{
        if(typeof callback==='function') callback(result.data);
      })
    }
  }).catch(res => {
    console.log(res);
  })
}

简直就是将一个方法copy + modify,然后还感觉自己工作充实~~但这就是**“坏味道的代码”**

Solutions

/**
 * Optimized simple get request
 * _get({url:"",params:{}},()=>{},()=>{})
 * @param request
 * @param success
 * @param failed
 * @private
 */
function _get(request, success, failed) {
  const req = createGetRequest(request);
  fetch(req).then(res => {
    if (res.ok) {
      res.json().then(result=>{
        if(typeof success==='function') success(result.data);
      })
    }else{
      if(typeof failed==='function') failed(res);
    }
  }).catch(res => {
     if(typeof failed==='function') failed(res);
  })
}

根据请求构造相应的url

function createGetRequest({url,params}){
  //Todo:check url and param type
  let req = url+"?";
  let query = [];
  if(params){
    Object.keys(params).forEach((key)=>{
     query.push(encodeURI(key)+"="+encodeURI(params[key]));
  });
  }
  return req+query.join("&");
}

Call

			   const {latitude,longitude} = res;//wx.getLocation
      	    _get({
                    url:GET.NearbyStores,
                    params:{latitude,longitude}
                  },res=>{
                    //todo: Save nearby stores to vuex
                    console.log(res)
                  },err=>{
                    //todo: error
                  })
                },

重构一下后感觉神清气爽

猜你喜欢

转载自blog.csdn.net/csu_passer/article/details/84995673