`
huakewoniu
  • 浏览: 46694 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

一个关于重构的小例子

阅读更多

重构(Refactoring)就是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更趋合理,提高软件的扩展性和维护性。

学会重构是一项非常重要的技能,写程序是一项艺术,我们的代码要尽可能的优雅。

 

下面是一个android的代码段 代码段是一个回调函数,回调函数中实现了很多的功能, 这段代码实现的功能是当用户点击UPDATE对应的按钮时,执行从URL指定的xml文件中取回数据,然后更新在ListView中, 这个程序段实现了这个功能但是仅仅实现功能是不够的,这段代码是相当丑陋的, 一个方法应该实现尽可能单一的功能,这不仅能让我们的代码的重用性更高,增强功能的扩展性,还能使我们的代码看起了更加的优雅

 

 

 public boolean onOptionsItemSelected(MenuItem item) {
  // 相应用户的点击信息,下载相应的mp3
  if(item.getItemId() == UPDATE ){
   

  }else if(item.getItemId() == ABOUT){
     //下载包含MP3基本信息的文件
 String xml = downloadXML(URL);
 //对xml文件进行解析,并将解析的结果放到Mp3Infor中
 List<Mp3Infor> mp3Infors = parse(xml);
 //生成一个List对象,并按照SimpleAdapter要求生成map;

 List<HashMap<String, String>> list =  new ArrayList<HashMap<String, String>>();
 for(Iterator iterator = mp3Infors.iterator(); iterator.hasNext();){
  Mp3Infor mp3Infor = (Mp3Infor)iterator.next();
  HashMap<String, String>  map = new HashMap<String, String>();
  map.put("mp3_name", mp3Infor.getMp3Name());
  map.put("mp3_size", mp3Infor.getMp3Size());
  list.add(map);
 }
 
 SimpleAdapter simpleAdapter = new SimpleAdapter(
   this,
   list,
   R.layout.mp3info_item,
   new String[]{"mp3_name", "mp3_size"},
   new int[]{R.id.mp3_name, R.id.mp3_size});
 setListAdapter(simpleAdapter );  
  }
  return super.onOptionsItemSelected(item);
 }

 

现在我们就来实现重构

 

private void updateListView(){
 //下载包含MP3基本信息的文件
 String xml = downloadXML(URL);
 //对xml文件进行解析,并将解析的结果放到Mp3Infor中
 List<Mp3Infor> mp3Infors = parse(xml);
 //生成一个List对象,并按照SimpleAdapter要求生成map;
 setListAdapter(buildSimpleAdapter(mp3Infors)); 
}

 

 

private SimpleAdapter buildSimpleAdapter(List<Mp3Infor> mp3Infors){
 List<HashMap<String, String>> list =  new ArrayList<HashMap<String, String>>();
 for(Iterator iterator = mp3Infors.iterator(); iterator.hasNext();){
  Mp3Infor mp3Infor = (Mp3Infor)iterator.next();
  HashMap<String, String>  map = new HashMap<String, String>();
  map.put("mp3_name", mp3Infor.getMp3Name());
  map.put("mp3_size", mp3Infor.getMp3Size());
  list.add(map);
 }
 
 SimpleAdapter simpleAdapter = new SimpleAdapter(
   this,
   list,
   R.layout.mp3info_item,
   new String[]{"mp3_name", "mp3_size"},
   new int[]{R.id.mp3_name, R.id.mp3_size});
 return simpleAdapter;
}

 

 

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // 相应用户的点击信息,下载相应的mp3
  if(item.getItemId() == UPDATE ){
   updateListView();
  }else if(item.getItemId() == ABOUT){
   
  }
  return super.onOptionsItemSelected(item);
 }

 

看看这样以来 我们的回调函数就显得多么的优雅, 而且updateListView 方法可以在其它地方调用, 需要修改时也只需要修改updateListView 这个方法就行了。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics