---
title: "编码最佳实践系列之一"
author: "aaronjiu_00"
date: "2008-10-23T11:28:28Z"
tags: ["Eclipse", "IDE", "UP"]
slug: "untitled"
draft: false
lastmod: "2008-10-23T11:28:28Z"
id: 256882
url: "https://tonglin.iteye.com/blog/256882"
---

- 避免空指针：
  
  ```
  /**
    * 判断应用是否有月租
    *
    * @param onlineProfile
    * @return 有月租返回true，无月租返回false
    */
  private boolean isAppHasRent(AppOnlineProfile onlineProfile) {
      return onlineProfile == null ? false : "y".equals(onlineProfile.getHasRent());
  }
  ```
- 集合List转换为数组\[]
  
  ```
  /**
    * 从应用订购列表中获得用户Id数组
    *
    * @param appSubscList 应用订购列表
    * @return 返回用户Id数组
    */
  private String[] getUserIds(final List<AppSubsc> appSubscList) {
      List<String> resultList = new ArrayList<String>(appSubscList.size());
      for (AppSubsc appSubsc : appSubscList) {
          resultList.add(appSubsc.getUser().getUserId());
      }
      return resultList.toArray(new String[resultList.size()]);
  }
  ```
- 枚举的遍历
  
  ```
  /**
    * 更改应用订购列表里面每个订单的订购者的LongId，其中LongId去除域名前缀
    *
    * @param appSubscList 应用订购列表
    * @return 返回更改LongId后的应用订购列表
    */
  private List<AppSubsc> setLongIds(final List<AppSubsc> appSubscList) {
      List<AppSubsc> resultList = new ArrayList<AppSubsc>(appSubscList);
      UserIdentifier[] userIdentifiers = userService.getUserIdentifiers(getUserIds(appSubscList));
      if (userIdentifiers != null) {
          for (int i = 0; i < userIdentifiers.length; i++) {
              final String longId = userIdentifiers[i].getLongId();
              for (DomainPrefix domainPrefix : DomainPrefix.values()) {
                  if (longId.startsWith(domainPrefix.name())){
                      resultList.get(i).getUser().setLongId(longId.substring(domainPrefix.name().length()));
                      break;
                  }
              }
          }
      }
      return resultList;
  }
  ```
- 方法的重载，HowToDo? 
  
  首先，选中类中需要重载的方法，(如果选中的方法是接口声明中方法实现的话，会出现询问框，选择Yes), 然后通过菜单栏"Refactor -&gt; Change Method Signature ..."，  
  或者上下文菜单"Refactor -&gt; Change Method Signature ..."，或者快捷键"Alt + Shift + C"，将会弹出"Change Method Signature"对话框，  
  在"参数"选项卡（默认会出现），单击右侧的"Add"按钮，添加一个参数，例如可以添加一个字符串参数：Type为String，Name为corpId，默认值为null  
  （如果Type是数值，可以是0或者任何能表示空概念的值），注意勾选复选框"Kepp original method as delegate to change method", 点击"Preview"按钮预览结果，  
  或者直接点击"OK"，直到完成重构。
  
  请大家关注重构后的结果，可以注意到接口里面也自动添加了方法签名，而且原来接口声明中的方法实现都会委托给这个新建的方法中，大家想想这样做有什么好处？
  
  当然你也可以通过编码@Deprecated原来的方法，或者在先前的"Change Method Signature"对话框中，勾选复选框"Marks as deprecated"；  
  如果将来不在需要这个@Deprecated的方法时，可以将原来的方法"Inline"掉
- 断言的使用（基于org.springframework.util.Assert）
  
  ```
  Assert.notNull(appSubsc, "appSubsc must not be null"); Assert.notNull(appSubsc.getUser(), "appSubsc.user must not be null");
  
  Assert.notNull(appSubsc.getUser().getUserId(), "appSubsc.user.userId must not be null");
  Assert.notNull(appSubsc.getUser().getName(), "appSubsc.user.name must not be null");
  
  Assert.notNull(appSubsc.getApp(), "appSubsc.app must not be null");
  Assert.notNull(appSubsc.getApp().getId(), "appSubsc.app.appId must not be null");
  Assert.notNull(appSubsc.getApp().getIsvId(), "appSubsc.app.isvId must not be null");
  
  Assert.hasText(appSubsc.getAppInstanceId(), "appSubsc.appInstanceId must not be empty");
  ```
- 先写类，还是先写接口？
  
  我想很多同学都是在先写接口，然后再写这个接口的实现类，这是几乎所有人的做法。
  
  我的思路很特别，我先写类，然后再通过重构这门"艺术"，如果有需要才"提取"为"接口"，如何提取接口？
  
  首先，选中类名，通过菜单栏"Refactor -&gt; Extract interface..."，或者上下文菜单"Refactor -&gt; Extract interface..."，打开"Extract interface"对话框，  
  先不用关注提取接口存放的位置（将来可以"Move"到恰当的位置，），直接输入"Interface name"（不用输入包名），点击"Preview"按钮，或者点击"OK"按钮完成接口的提取。
  
  如果有需求在已有接口中新增几个方法，或者要新增的方法已经在实现类中存在，怎么办？难道要手工在接口代码中添加方法，然后再实现这些接口声明吗，事实上大部分同学是这么做的。
  
  我则不然！我可以利用我们的利器"Eclipse IDE"，我还是从【实现】类开始，新增方法，你就直接编写新的方法好了，如果已经存在了，就不必写了。  
  然后在接口的实现类中，选中想要作为接口暴露的方法，通过菜单栏"Refactor -&gt; Pull up..."，或者上下文菜单"Refactor -&gt; Pull up..."，弹出"Pull Up"对话框，  
  选择"destination type"和"members to pull up"，把这个方法提升为接口中的方法，具体可以看我的现场演示，请大家大胆使用重构这门"艺术"，会给大家带来"快感"