Skip to content

Instantly share code, notes, and snippets.

@yangyi
Last active December 16, 2015 11:18
Show Gist options
  • Save yangyi/5426040 to your computer and use it in GitHub Desktop.
Save yangyi/5426040 to your computer and use it in GitHub Desktop.

原则

  1. 代码看上去很清楚在做什么事情. 不要写注释来说明程序在做什么, 而是要把程序逻辑写的非常清楚.

    a. 为啥isPlaying了还要play()呢?

     	public boolean movePrevious()
     	{
     	 if(playIndex > 0)
     	 {
     	  boolean isPlaying = isPlaying();
     	  playIndex--;
     	  try
     	  {
     	   setPlayIndex(playIndex);
     	   if(isPlaying) 
     	   {
     	    play();
     	   }
     	  }
    

b. 比如这里, 为啥需要isPlaying和paused两个状态呢? paused难道不是isPlaying正好相反么? 有buffer状态么? 如果有buffer状态, 是不是用一个state, 声明enum STATE { playing, buffering, pause, stop} 这样的状态更好?

    public void pause()
    {
     isPlaying = false;
     paused = true;
     mediaPlayer.pause();
    } 
  1. 小心重复代码. 重复太多了就需要抽象, 抽象的方向是业务逻辑. a. 这样我们在UI中使用的代码只需要关心最少的状态, 比如抽象出ShareManager, FavoriteManager, 以及下面的AudioListPlayer sample code b. 避免重复

  2. 先关心接口, 再关心实现, 见 https://gist.github.com/yangyi/5426036

Guidelines

  1. 关于注释. a. 要把程序逻辑写清楚, 尽量不要写注释. b. 写why, 不要写what.

  2. 转换json的时候, 不要如下copy paste.

     //用gson,  
     AudioColumn audioColumn = gson.fromJson(json);
     
     //不要反复set, 这个应该在网络处理层完成
     audioColumnDetail.setId(jsonObject.optString("_id"));
     audioColumnDetail.setTitle(jsonObject.optString("title"));
     audioColumnDetail.setPrice(jsonObject.optInt("price"));
     audioColumnDetail.setSeconds(jsonObject.optInt("seconds"));
     audioColumnDetail.setImageUrl(jsonObject.optString("image_url"));
     audioColumnDetail.setCreatedAt(jsonObject.optString("created_at"));
     audioColumnDetail.setContentUrl(jsonObject.optString("content_url"));
    
  3. 所有Exception的处理, 不能是e.printStackTrace(); 这样会吞噬错误, 真有问题的时候不容易发现. 需要将Checked Exception 全部转换成RuntimeException

     e.printStackTrace() 全部改成 throw new RuntimeException(e)
    
  4. 逻辑尽量独立, 比如一个Activity有3个以上点击事件, 那么就不要把这3个点击事件的处理都放在Activity的onClick方法中, 很难对应button和相应的onClickListener.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment