<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          阿里精選:Java 代碼精簡之道

          共 27958字,需瀏覽 56分鐘

           ·

          2020-08-31 19:13


          Photo?@??Priscilla Du Preez?

          文? |??常意

          前言




          古語有云:

          道為術(shù)之靈,術(shù)為道之體;以道統(tǒng)術(shù),以術(shù)得道。


          其中:“道”指“規(guī)律、道理、理論”,“術(shù)”指“方法、技巧、技術(shù)”。意思是:“道”是“術(shù)”的靈魂,“術(shù)”是“道”的肉體;可以用“道”來統(tǒng)管“術(shù)”,也可以從“術(shù)”中獲得“道”。

          在拜讀大佬“孤盡”的文章《Code Review是苦澀但有意思的修行》時(shí),感受最深的一句話就是:“優(yōu)質(zhì)的代碼一定是少即是多的精兵原則”,這就是大佬的代碼精簡之“道”。

          工匠追求“術(shù)”到極致,其實(shí)就是在尋“道”,且離悟“道”也就不遠(yuǎn)了,亦或是已經(jīng)得道,這就是“工匠精神”——一種追求“以術(shù)得道”的精神。如果一個(gè)工匠只滿足于“術(shù)”,不能追求“術(shù)”到極致去悟“道”,那只是一個(gè)靠“術(shù)”養(yǎng)家糊口的工匠而已。作者根據(jù)多年來的實(shí)踐探索,總結(jié)了大量的 Java 代碼精簡之“術(shù)”,試圖闡述出心中的 Java 代碼精簡之“道”。


          1.利用語法




          1.1.利用三元表達(dá)式

          普通:


          String title;if (isMember(phone)) {    title = "會(huì)員";} else {    title = "游客";}
          精簡:
          String title = isMember(phone) ? "會(huì)員" : "游客";


          注意:對于包裝類型的算術(shù)計(jì)算,需要注意避免拆包時(shí)的空指針問題。


          1.2.利用 for-each 語句


          從 Java 5 起,提供了 for-each 循環(huán),簡化了數(shù)組和集合的循環(huán)遍歷。 for-each? 循環(huán)允許你無需保持傳統(tǒng) for 循環(huán)中的索引就可以遍歷數(shù)組,或在使用迭代器時(shí)無需在 while 循環(huán)中調(diào)用 hasNext 方法和 next 方法就可以遍歷集合。
          普通:
          double[] values = ...;for(int i = 0; i < values.length; i++) {    double value = values[i];    // TODO: 處理value}
          List valueList = ...;Iterator iterator = valueList.iterator();while (iterator.hasNext()) { Double value = iterator.next(); // TODO: 處理value}

          精簡:
          double[] values = ...;for(double value : values) {    // TODO: 處理value}
          List valueList = ...;for(Double value : valueList) { // TODO: 處理value}

          1.3.利用 try-with-resource 語句

          所有實(shí)現(xiàn) Closeable 接口的“資源”,均可采用 try-with-resource 進(jìn)行簡化。

          普通:
          BufferedReader reader = null;try {    reader = new BufferedReader(new FileReader("cities.csv"));    String line;    while ((line = reader.readLine()) != null) {        // TODO: 處理line    }} catch (IOException e) {    log.error("讀取文件異常", e);} finally {    if (reader != null) {        try {            reader.close();        } catch (IOException e) {            log.error("關(guān)閉文件異常", e);        }    }}


          精簡:
          try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {    String line;    while ((line = reader.readLine()) != null) {        // TODO: 處理line    }} catch (IOException e) {    log.error("讀取文件異常", e);}

          1.4.利用 return 關(guān)鍵字


          利用 return 關(guān)鍵字,可以提前函數(shù)返回,避免定義中間變量。

          普通:
          public static boolean hasSuper(@NonNull List userList) {    boolean hasSuper = false;    for (UserDO user : userList) {        if (Boolean.TRUE.equals(user.getIsSuper())) {            hasSuper = true;            break;        }    }    return hasSuper;}


          精簡:
          public static boolean hasSuper(@NonNull List userList) {    for (UserDO user : userList) {        if (Boolean.TRUE.equals(user.getIsSuper())) {            return true;        }    }    return false;}

          1.5.利用 static 關(guān)鍵字


          利用 static 關(guān)鍵字,可以把字段變成靜態(tài)字段,也可以把函數(shù)變?yōu)殪o態(tài)函數(shù),調(diào)用時(shí)就無需初始化類對象。

          普通:
          public final class GisHelper {    public double distance(double lng1, double lat1, double lng2, double lat2) {        // 方法實(shí)現(xiàn)代碼    }}

          GisHelper gisHelper = new GisHelper();double distance = gisHelper.distance(116.178692D, 39.967115D, 116.410778D, 39.899721D);



          精簡:
          public final class GisHelper {    public static double distance(double lng1, double lat1, double lng2, double lat2) {        // 方法實(shí)現(xiàn)代碼    }}
          double distance = GisHelper.distance(116.178692D, 39.967115D, 116.410778D, 39.899721D);



          1.6.利用 lambda 表達(dá)式


          Java 8 發(fā)布以后,lambda 表達(dá)式大量替代匿名內(nèi)部類的使用,在簡化了代碼的同時(shí),更突出了原有匿名內(nèi)部類中真正有用的那部分代碼。

          普通:
          new Thread(new Runnable() {    public void run() {        // 線程處理代碼    }}).start();


          精簡:
          new Thread(() -> {    // 線程處理代碼}).start();

          1.7.利用方法引用


          方法引用(::),可以簡化 lambda 表達(dá)式,省略變量聲明和函數(shù)調(diào)用。
          普通:
          Arrays.sort(nameArray, (a, b) -> a.compareToIgnoreCase(b));List userIdList = userList.stream()    .map(user -> user.getId())    .collect(Collectors.toList());

          精簡:
          Arrays.sort(nameArray, String::compareToIgnoreCase);List userIdList = userList.stream()    .map(UserDO::getId)    .collect(Collectors.toList());


          1.8.利用靜態(tài)導(dǎo)入


          靜態(tài)導(dǎo)入(import static),當(dāng)程序中大量使用同一靜態(tài)常量和函數(shù)時(shí),可以簡化靜態(tài)常量和函數(shù)的引用。

          普通:
          List areaList = radiusList.stream().map(r -> Math.PI * Math.pow(r, 2)).collect(Collectors.toList());...


          精簡:
          import static java.lang.Math.PI;import static java.lang.Math.pow;import static java.util.stream.Collectors.toList;
          List areaList = radiusList.stream().map(r -> PI * pow(r, 2)).collect(toList());...


          注意:靜態(tài)引入容易造成代碼閱讀困難,所以在實(shí)際項(xiàng)目中應(yīng)該警慎使用。


          1.9.利用 unchecked 異常


          Java 的異常分為兩類:Checked 異常和 Unchecked 異常。Unchecked 異常繼承了RuntimeException ,特點(diǎn)是代碼不需要處理它們也能通過編譯,所以它們稱作? Unchecked 異常。利用 Unchecked 異常,可以避免不必要的 try-catch 和 throws 異常處理。

          普通:
          @Servicepublic class UserService {    public void createUser(UserCreateVO create, OpUserVO user) throws BusinessException {        checkOperatorUser(user);        ...    }    private void checkOperatorUser(OpUserVO user) throws BusinessException {        if (!hasPermission(user)) {            throw new BusinessException("用戶無操作權(quán)限");        }        ...    }    ...}
          @RestController@RequestMapping("/user")public class UserController { @Autowired private UserService userService;
          @PostMapping("/createUser") public Result createUser(@RequestBody @Valid UserCreateVO create, OpUserVO user) throws BusinessException { userService.createUser(create, user); return Result.success(); } ...}


          精簡:
          @Servicepublic class UserService {    public void createUser(UserCreateVO create, OpUserVO user) {        checkOperatorUser(user);        ...    }    private void checkOperatorUser(OpUserVO user) {        if (!hasPermission(user)) {            throw new BusinessRuntimeException("用戶無操作權(quán)限");        }        ...    }    ...}
          @RestController@RequestMapping("/user")public class UserController { @Autowired private UserService userService;
          @PostMapping("/createUser") public Result createUser(@RequestBody @Valid UserCreateVO create, OpUserVO user) { userService.createUser(create, user); return Result.success(); } ...}




          2.利用注解




          2.1.利用 Lombok 注解


          Lombok 提供了一組有用的注解,可以用來消除Java類中的大量樣板代碼。

          普通:
          public class UserVO {    private Long id;    private String name;    public Long getId() {        return this.id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return this.name;    }    public void setName(String name) {        this.name = name;    }    ...}


          精簡:
          @Getter@Setter@ToStringpublic class UserVO {    private Long id;    private String name;    ...}

          2.2.利用 Validation 注解



          普通:
          @Getter@Setter@ToStringpublic class UserCreateVO {    @NotBlank(message = "用戶名稱不能為空")    private String name;    @NotNull(message = "公司標(biāo)識(shí)不能為空")    private Long companyId;    ...}@Service@Validatedpublic class UserService {    public Long createUser(@Valid UserCreateVO create) {        // TODO: 創(chuàng)建用戶        return null;    }}
          ?


          精簡:
          @Getter@Setter@ToStringpublic class UserCreateVO {    @NotBlank(message = "用戶名稱不能為空")    private String name;    @NotNull(message = "公司標(biāo)識(shí)不能為空")    private Long companyId;    ...}
          @Service@Validatedpublic class UserService { public Long createUser(@Valid UserCreateVO create) { // TODO: 創(chuàng)建用戶 return null; }}



          2.3.利用 @NonNull 注解



          Spring 的 @NonNull 注解,用于標(biāo)注參數(shù)或返回值非空,適用于項(xiàng)目內(nèi)部團(tuán)隊(duì)協(xié)作。只要實(shí)現(xiàn)方和調(diào)用方遵循規(guī)范,可以避免不必要的空值判斷,這充分體現(xiàn)了阿里的“新六脈神劍”提倡的“因?yàn)樾湃危院唵巍薄?/span>

          普通:
          public List queryCompanyUser(Long companyId) {    // 檢查公司標(biāo)識(shí)    if (companyId == null) {        return null;    }
          // 查詢返回用戶 List userList = userDAO.queryByCompanyId(companyId); return userList.stream().map(this::transUser).collect(Collectors.toList());}
          Long companyId = 1L;List userList = queryCompanyUser(companyId);if (CollectionUtils.isNotEmpty(userList)) { for (UserVO user : userList) { // TODO: 處理公司用戶 }}


          精簡:
          public @NonNull List queryCompanyUser(@NonNull Long companyId) {    List userList = userDAO.queryByCompanyId(companyId);    return userList.stream().map(this::transUser).collect(Collectors.toList());}
          Long companyId = 1L;List userList = queryCompanyUser(companyId);for (UserVO user : userList) { // TODO: 處理公司用戶}


          2.4.利用注解特性


          注解有以下特性可用于精簡注解聲明:
          1、當(dāng)注解屬性值跟默認(rèn)值一致時(shí),可以刪除該屬性賦值;
          2、當(dāng)注解只有value屬性時(shí),可以去掉value進(jìn)行簡寫;
          3、當(dāng)注解屬性組合等于另一個(gè)特定注解時(shí),直接采用該特定注解。

          普通:
          @Lazy(true);@Service(value = "userService")@RequestMapping(path = "/getUser", method = RequestMethod.GET)




          精簡:
          @Lazy@Service("userService")@GetMapping("/getUser")



          3.利用泛型




          3.1.泛型接口


          在 Java 沒有引入泛型前,都是采用 Object 表示通用對象,最大的問題就是類型無法強(qiáng)校驗(yàn)并且需要強(qiáng)制類型轉(zhuǎn)換。



          普通:
          public interface Comparable {    public int compareTo(Object other);}
          @Getter@Setter@ToStringpublic class UserVO implements Comparable { private Long id;
          @Override public int compareTo(Object other) { UserVO user = (UserVO)other; return Long.compare(this.id, user.id); }}



          精簡:
          public interface Comparable {    public int compareTo(T other);}
          @Getter@Setter@ToStringpublic class UserVO implements Comparable { private Long id;
          @Override public int compareTo(UserVO other) { return Long.compare(this.id, other.id); }}




          3.2.泛型類


          普通:
          @Getter@Setter@ToStringpublic class IntPoint {    private Integer x;    private Integer y;}
          @Getter@Setter@ToStringpublic class DoublePoint { private Double x; private Double y;}



          精簡:
          @Getter@Setter@ToStringpublic class Point {    private T x;    private T y;}


          3.3.泛型方法


          普通:
          public static Map newHashMap(String[] keys, Integer[] values) {    // 檢查參數(shù)非空    if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {        return Collections.emptyMap();    }
          // 轉(zhuǎn)化哈希映射 Map map = new HashMap<>(); int length = Math.min(keys.length, values.length); for (int i = 0; i < length; i++) { map.put(keys[i], values[i]); } return map;}...



          精簡:
          public static  Map newHashMap(K[] keys, V[] values) {    // 檢查參數(shù)非空    if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {        return Collections.emptyMap();    }
          // 轉(zhuǎn)化哈希映射 Map map = new HashMap<>(); int length = Math.min(keys.length, values.length); for (int i = 0; i < length; i++) { map.put(keys[i], values[i]); } return map;}





          4.利用自身方法




          4.1.利用構(gòu)造方法


          構(gòu)造方法,可以簡化對象的初始化和設(shè)置屬性操作。對于屬性字段較少的類,可以自定義構(gòu)造方法。

          普通:
          @Getter@Setter@ToStringpublic class PageDataVO {    private Long totalCount;    private List dataList;}
          PageDataVO pageData = new PageDataVO<>();pageData.setTotalCount(totalCount);pageData.setDataList(userList);return pageData;



          精簡:
          @Getter@Setter@ToString@NoArgsConstructor@AllArgsConstructorpublic class PageDataVO {    private Long totalCount;    private List dataList;}
          return new PageDataVO<>(totalCount, userList);



          注意:如果屬性字段被替換時(shí),存在構(gòu)造函數(shù)初始化賦值問題。比如把屬性字段title替換為 nickname ,由于構(gòu)造函數(shù)的參數(shù)個(gè)數(shù)和類型不變,原有構(gòu)造函數(shù)初始化語句不會(huì)報(bào)錯(cuò),導(dǎo)致把原title值賦值給 nickname 。如果采用 Setter 方法賦值,編譯器會(huì)提示錯(cuò)誤并要求修復(fù)。


          4.2.利用 Set 的 add 方法


          利用 Set 的 add 方法的返回值,可以直接知道該值是否已經(jīng)存在,可以避免調(diào)用 contains 方法判斷存在。

          普通:
          以下案例是進(jìn)行用戶去重轉(zhuǎn)化操作,需要先調(diào)用 contains 方法判斷存在,后調(diào)用add方法進(jìn)行添加。

          Set userIdSet = new HashSet<>();List userVOList = new ArrayList<>();for (UserDO userDO : userDOList) {    if (!userIdSet.contains(userDO.getId())) {        userIdSet.add(userDO.getId());        userVOList.add(transUser(userDO));    }}



          精簡:
          SSet userIdSet = new HashSet<>();List userVOList = new ArrayList<>();for (UserDO userDO : userDOList) {    if (userIdSet.add(userDO.getId())) {        userVOList.add(transUser(userDO));    }}

          ?


          4.3.利用 Map 的 computeIfAbsent?方法



          利用 Map 的 computeIfAbsent 方法,可以保證獲取到的對象非空,從而避免了不必要的空判斷和重新設(shè)置值。

          普通:
          Map> roleUserMap = new HashMap<>();for (UserDO userDO : userDOList) {    Long roleId = userDO.getRoleId();    List userList = roleUserMap.get(roleId);    if (Objects.isNull(userList)) {        userList = new ArrayList<>();        roleUserMap.put(roleId, userList);    }    userList.add(userDO);}



          精簡:
          Map> roleUserMap = new HashMap<>();for (UserDO userDO : userDOList) {    roleUserMap.computeIfAbsent(userDO.getRoleId(), key -> new ArrayList<>())        .add(userDO);}


          4.4.利用鏈?zhǔn)骄幊?/span>



          鏈?zhǔn)骄幊?,也叫級?lián)式編程,調(diào)用對象的函數(shù)時(shí)返回一個(gè)this對象指向?qū)ο蟊旧恚_(dá)到鏈?zhǔn)叫Ч?,可以級?lián)調(diào)用。鏈?zhǔn)骄幊痰膬?yōu)點(diǎn)是:編程性強(qiáng)、可讀性強(qiáng)、代碼簡潔。

          普通:
          StringBuilder builder = new StringBuilder(96);builder.append("select id, name from ");builder.append(T_USER);builder.append(" where id = ");builder.append(userId);builder.append(";");



          精簡:
          StringBuilder builder = new StringBuilder(96);builder.append("select id, name from ")    .append(T_USER)    .append(" where id = ")    .append(userId)    .append(";");





          5.利用工具方法




          5.1.避免空值判斷


          普通:
          if (userList != null && !userList.isEmpty()) {    // TODO: 處理代碼}



          精簡:
          if (CollectionUtils.isNotEmpty(userList)) {    // TODO: 處理代碼}


          5.2.避免條件判斷


          普通:
          double result;if (value <= MIN_LIMIT) {    result = MIN_LIMIT;} else {    result = value;}



          精簡:
          double result = Math.max(MIN_LIMIT, value);


          5.3.簡化賦值語句



          普通:
          public static final List ANIMAL_LIST;static {    List animalList = new ArrayList<>();    animalList.add("dog");    animalList.add("cat");    animalList.add("tiger");    ANIMAL_LIST = Collections.unmodifiableList(animalList);}



          精簡:
          // JDK流派public static final List ANIMAL_LIST = Arrays.asList("dog", "cat", "tiger");// Guava流派public static final List ANIMAL_LIST = ImmutableList.of("dog", "cat", "tiger");

          注意:Arrays.asList 返回的 List 并不是 ArrayList ,不支持 add 等變更操作。


          5.4.簡化數(shù)據(jù)拷貝



          普通:
          UserVO userVO = new UserVO();userVO.setId(userDO.getId());userVO.setName(userDO.getName());...userVO.setDescription(userDO.getDescription());userVOList.add(userVO);



          精簡:
          UserVO userVO = new UserVO();BeanUtils.copyProperties(userDO, userVO);userVOList.add(userVO);



          反例:
          List userVOList = JSON.parseArray(JSON.toJSONString(userDOList), UserVO.class);



          精簡代碼,但不能以過大的性能損失為代價(jià)。例子是淺層拷貝,用不著 JSON 這樣重量級的武器。


          5.5.簡化異常斷言


          普通:
          if (Objects.isNull(userId)) {    throw new IllegalArgumentException("用戶標(biāo)識(shí)不能為空");}



          精簡:
          Assert.notNull(userId, "用戶標(biāo)識(shí)不能為空");



          注意:可能有些插件不認(rèn)同這種判斷,導(dǎo)致使用該對象時(shí)會(huì)有空指針警告。


          5.6.簡化測試用例


          把測試用例數(shù)據(jù)以 JSON 格式存入文件中,通過 JSON 的 parseObject 和 parseArray 方法解析成對象。雖然執(zhí)行效率上有所下降,但可以減少大量的賦值語句,從而精簡了測試代碼。

          普通:
          @Testpublic void testCreateUser() {    UserCreateVO userCreate = new UserCreateVO();    userCreate.setName("Changyi");    userCreate.setTitle("Developer");    userCreate.setCompany("AMAP");    ...    Long userId  = userService.createUser(OPERATOR, userCreate);    Assert.assertNotNull(userId, "創(chuàng)建用戶失敗");}

          精簡:
          @Testpublic void testCreateUser() {    String jsonText = ResourceHelper.getResourceAsString(getClass(), "createUser.json");    UserCreateVO userCreate = JSON.parseObject(jsonText, UserCreateVO.class);    Long userId  = userService.createUser(OPERATOR, userCreate);    Assert.assertNotNull(userId, "創(chuàng)建用戶失敗");}



          建議:JSON 文件名最好以被測試的方法命名,如果有多個(gè)版本可以用數(shù)字后綴表示。


          5.7.簡化算法實(shí)現(xiàn)



          一些常規(guī)算法,已有現(xiàn)成的工具方法,我們就沒有必要自己實(shí)現(xiàn)了。

          普通:
          int totalSize = valueList.size();List> partitionList = new ArrayList<>();for (int i = 0; i < totalSize; i += PARTITION_SIZE) {    partitionList.add(valueList.subList(i, Math.min(i + PARTITION_SIZE, totalSize)));}




          精簡:

          List> partitionList = ListUtils.partition(valueList, PARTITION_SIZE);



          5.8.封裝工具方法


          一些特殊算法,沒有現(xiàn)成的工具方法,我們就只好自己親自實(shí)現(xiàn)了。

          普通:
          比如,SQL 設(shè)置參數(shù)值的方法就比較難用,setLong 方法不能設(shè)置參數(shù)值為 null 。
           // 設(shè)置參數(shù)值if (Objects.nonNull(user.getId())) {  statement.setLong(1, user.getId());} else {    statement.setNull(1, Types.BIGINT);}...

          精簡:
          我們可以封裝為一個(gè)工具類 SqlHelper ,簡化設(shè)置參數(shù)值的代碼。


          /** SQL輔助類 */public final class SqlHelper {    /** 設(shè)置長整數(shù)值 */    public static void setLong(PreparedStatement statement, int index, Long value) throws SQLException {        if (Objects.nonNull(value)) {            statement.setLong(index, value.longValue());        } else {            statement.setNull(index, Types.BIGINT);        }    }    ...}
          // 設(shè)置參數(shù)值SqlHelper.setLong(statement, 1, user.getId());




          6.利用數(shù)據(jù)結(jié)構(gòu)



          6.1.利用數(shù)組簡化



          對于固定上下限范圍的 if-else 語句,可以用數(shù)組+循環(huán)來簡化。
          普通:
          public static int getGrade(double score) {    if (score >= 90.0D) {        return 1;    }    if (score >= 80.0D) {        return 2;    }    if (score >= 60.0D) {        return 3;    }    if (score >= 30.0D) {        return 4;    }    return 5;}



          精簡:
          private static final double[] SCORE_RANGES = new double[] {90.0D, 80.0D, 60.0D, 30.0D};public static int getGrade(double score) {    for (int i = 0; i < SCORE_RANGES.length; i++) {        if (score >= SCORE_RANGES[i]) {            return i + 1;        }    }    return SCORE_RANGES.length + 1;}



          思考:上面的案例返回值是遞增的,所以用數(shù)組簡化是沒有問題的。但是,如果返回值不是遞增的,能否用數(shù)組進(jìn)行簡化呢?答案是可以的,請自行思考解決。


          6.2.利用 Map 簡化


          對于映射關(guān)系的 if-else 語句,可以用Map來簡化。此外,此規(guī)則同樣適用于簡化映射關(guān)系的 switch 語句。

          普通:
          public static String getBiologyClass(String name) {    switch (name) {        case "dog" :            return "animal";        case "cat" :            return "animal";        case "lavender" :            return "plant";        ...        default :            return null;    }}

          精簡:
          private static final Map BIOLOGY_CLASS_MAP    = ImmutableMap.builder()        .put("dog", "animal")        .put("cat", "animal")        .put("lavender", "plant")        ...        .build();public static String getBiologyClass(String name) {    return BIOLOGY_CLASS_MAP.get(name);}



          已經(jīng)把方法簡化為一行代碼,其實(shí)都沒有封裝方法的必要了。


          6.3.利用容器類簡化


          Java 不像 Python 和 Go ,方法不支持返回多個(gè)對象。如果需要返回多個(gè)對象,就必須自定義類,或者利用容器類。常見的容器類有 Apache 的 Pair 類和 Triple 類, Pair 類支持返回 2 個(gè)對象, Triple 類支持返回 3 個(gè)對象。

          普通:
          @Setter@Getter@ToString@AllArgsConstructorpublic static class PointAndDistance {    private Point point;    private Double distance;}
          public static PointAndDistance getNearest(Point point, Point[] points) { // 計(jì)算最近點(diǎn)和距離 ...
          // 返回最近點(diǎn)和距離 return new PointAndDistance(nearestPoint, nearestDistance);}



          精簡:
          public static Pair getNearest(Point point, Point[] points) {    // 計(jì)算最近點(diǎn)和距離    ...
          // 返回最近點(diǎn)和距離 return ImmutablePair.of(nearestPoint, nearestDistance);}


          6.4.利用 ThreadLocal 簡化



          ThreadLocal 提供了線程專有對象,可以在整個(gè)線程生命周期中隨時(shí)取用,極大地方便了一些邏輯的實(shí)現(xiàn)。用 ThreadLocal 保存線程上下文對象,可以避免不必要的參數(shù)傳遞。

          普通:
          由于 DateFormat 的 format 方法線程非安全(建議使用替代方法),在線程中頻繁初始化 DateFormat 性能太低,如果考慮重用只能用參數(shù)傳入 DateFormat 。例子如下:


          public static String formatDate(Date date, DateFormat format) {    return format.format(date);}
          public static List getDateList(Date minDate, Date maxDate, DateFormat format) { List dateList = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(minDate); String currDate = formatDate(calendar.getTime(), format); String maxsDate = formatDate(maxDate, format); while (currDate.compareTo(maxsDate) <= 0) { dateList.add(currDate); calendar.add(Calendar.DATE, 1); currDate = formatDate(calendar.getTime(), format); } return dateList;}

          精簡:
          可能你會(huì)覺得以下的代碼量反而多了,如果調(diào)用工具方法的地方比較多,就可以省下一大堆 DateFormat 初始化和傳入?yún)?shù)的代碼。


          private static final ThreadLocal LOCAL_DATE_FORMAT = new ThreadLocal() {    @Override    protected DateFormat initialValue() {        return new SimpleDateFormat("yyyyMMdd");    }};
          public static String formatDate(Date date) { return LOCAL_DATE_FORMAT.get().format(date);}
          public static List getDateList(Date minDate, Date maxDate) { List dateList = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(minDate); String currDate = formatDate(calendar.getTime()); String maxsDate = formatDate(maxDate); while (currDate.compareTo(maxsDate) <= 0) { dateList.add(currDate); calendar.add(Calendar.DATE, 1); currDate = formatDate(calendar.getTime()); } return dateList;}



          注意:ThreadLocal 有一定的內(nèi)存泄露的風(fēng)險(xiǎn),盡量在業(yè)務(wù)代碼結(jié)束前調(diào)用 remove 方法進(jìn)行數(shù)據(jù)清除。




          7.利用?Optional



          在?Java 8?里,引入了一個(gè)?Optional?類,該類是一個(gè)可以為?null?的容器對象。


          7.1.保證值存在


          普通:
          Integer thisValue;if (Objects.nonNull(value)) {    thisValue = value;} else {    thisValue = DEFAULT_VALUE;}



          精簡:
          Integer thisValue = Optional.ofNullable(value).orElse(DEFAULT_VALUE);



          7.2.保證值合法



          普通:
          Integer thisValue;if (Objects.nonNull(value) && value.compareTo(MAX_VALUE) <= 0) {    thisValue = value;} else {    thisValue = MAX_VALUE;}

          精簡:
          Integer thisValue = Optional.ofNullable(value)    .filter(tempValue -> tempValue.compareTo(MAX_VALUE) <= 0).orElse(MAX_VALUE);



          7.3.避免空判斷


          普通:
          String zipcode = null;if (Objects.nonNull(user)) {    Address address = user.getAddress();    if (Objects.nonNull(address)) {        Country country = address.getCountry();        if (Objects.nonNull(country)) {            zipcode = country.getZipcode();        }    }}

          精簡:
          tring zipcode = Optional.ofNullable(user).map(User::getAddress)    .map(Address::getCountry).map(Country::getZipcode).orElse(null);




          8.利用 Stream




          流(Stream)是Java 8的新成員,允許你以聲明式處理數(shù)據(jù)集合,可以看成為一個(gè)遍歷數(shù)據(jù)集的高級迭代器。流主要有三部分構(gòu)成:獲取一個(gè)數(shù)據(jù)源→數(shù)據(jù)轉(zhuǎn)換→執(zhí)行操作獲取想要的結(jié)果。每次轉(zhuǎn)換原有 Stream 對象不改變,返回一個(gè)新的 Stream 對象,這就允許對其操作可以像鏈條一樣排列,形成了一個(gè)管道。流(Stream)提供的功能非常有用,主要包括匹配、過濾、匯總、轉(zhuǎn)化、分組、分組匯總等功能。




          8.1.匹配集合數(shù)據(jù)


          普通:
          boolean isFound = false;for (UserDO user : userList) {    if (Objects.equals(user.getId(), userId)) {        isFound = true;        break;    }}

          精簡:
          boolean isFound = userList.stream()    .anyMatch(user -> Objects.equals(user.getId(), userId));

          8.2.過濾集合數(shù)據(jù)

          普通:
          List resultList = new ArrayList<>();for (UserDO user : userList) {    if (Boolean.TRUE.equals(user.getIsSuper())) {        resultList.add(user);    }}

          精簡:
          List resultList = userList.stream()    .filter(user -> Boolean.TRUE.equals(user.getIsSuper()))    .collect(Collectors.toList());

          8.3.匯總集合數(shù)據(jù)

          普通:
          double total = 0.0D;for (Account account : accountList) {    total += account.getBalance();}

          精簡:
          double total = accountList.stream().mapToDouble(Account::getBalance).sum();



          8.4.轉(zhuǎn)化集合數(shù)據(jù)

          普通:
          List userVOList = new ArrayList<>();for (UserDO userDO : userDOList) {    userVOList.add(transUser(userDO));}

          精簡:
          List userVOList = userDOList.stream()    .map(this::transUser).collect(Collectors.toList());

          8.5.分組集合數(shù)據(jù)


          普通:
          Map> roleUserMap = new HashMap<>();for (UserDO userDO : userDOList) {    roleUserMap.computeIfAbsent(userDO.getRoleId(), key -> new ArrayList<>())        .add(userDO);}

          精簡:
          Map> roleUserMap = userDOList.stream()    .collect(Collectors.groupingBy(UserDO::getRoleId));

          8.6.分組匯總集合


          普通:
          Map roleTotalMap = new HashMap<>();for (Account account : accountList) {    Long roleId = account.getRoleId();    Double total = Optional.ofNullable(roleTotalMap.get(roleId)).orElse(0.0D);    roleTotalMap.put(roleId, total + account.getBalance());}

          精簡:
          roleTotalMap = accountList.stream().collect(Collectors.groupingBy(Account::getRoleId, Collectors.summingDouble(Account::getBalance)));



          8.7.生成范圍集合

          Python 的 range 非常方便,Stream 也提供了類似的方法。

          普通:
          int[] array1 = new int[N];for (int i = 0; i < N; i++) {    array1[i] = i + 1;}
          int[] array2 = new int[N];array2[0] = 1;for (int i = 1; i < N; i++) { array2[i] = array2[i - 1] * 2;}

          精簡:
          int[] array1 = IntStream.rangeClosed(1, N).toArray();int[] array2 = IntStream.iterate(1, n -> n * 2).limit(N).toArray();



          9.利用程序結(jié)構(gòu)


          9.1.返回條件表達(dá)式



          條件表達(dá)式判斷返回布爾值,條件表達(dá)式本身就是結(jié)果。

          普通:
          public boolean isSuper(Long userId)    UserDO user = userDAO.get(userId);    if (Objects.nonNull(user) && Boolean.TRUE.equals(user.getIsSuper())) {        return true;    }    return false;}

          精簡:
          public boolean isSuper(Long userId)    UserDO user = userDAO.get(userId);    return Objects.nonNull(user) && Boolean.TRUE.equals(user.getIsSuper());}


          9.2.最小化條件作用域


          最小化條件作用域,盡量提出公共處理代碼。

          普通:
          Result result = summaryService.reportWorkDaily(workDaily);if (result.isSuccess()) {    String message = "上報(bào)工作日報(bào)成功";    dingtalkService.sendMessage(user.getPhone(), message);} else {    String message = "上報(bào)工作日報(bào)失敗:" + result.getMessage();    log.warn(message);    dingtalkService.sendMessage(user.getPhone(), message);}

          精簡:
          String message;Result result = summaryService.reportWorkDaily(workDaily);if (result.isSuccess()) {    message = "上報(bào)工作日報(bào)成功";} else {    message = "上報(bào)工作日報(bào)失敗:" + result.getMessage();    log.warn(message);}dingtalkService.sendMessage(user.getPhone(), message);

          9.3.調(diào)整表達(dá)式位置



          調(diào)整表達(dá)式位置,在邏輯不變的前提下,讓代碼變得更簡潔。

          普通1:
          String line = readLine();while (Objects.nonNull(line)) {    ... // 處理邏輯代碼    line = readLine();}

          普通2:
          for (String line = readLine(); Objects.nonNull(line); line = readLine()) {    ... // 處理邏輯代碼}

          精簡:
          String line;while (Objects.nonNull(line = readLine())) {    ... // 處理邏輯代碼}

          注意:有些規(guī)范可能不建議這種精簡寫法。

          9.4.利用非空對象



          在比較對象時(shí),交換對象位置,利用非空對象,可以避免空指針判斷。

          普通:
          private static final int MAX_VALUE = 1000;boolean isMax = (value != null && value.equals(MAX_VALUE));boolean isTrue = (result != null && result.equals(Boolean.TRUE));



          精簡:
          private static final Integer MAX_VALUE = 1000;boolean isMax = MAX_VALUE.equals(value);boolean isTrue = Boolean.TRUE.equals(result);





          10.利用設(shè)計(jì)模式




          10.1.模板方法模式


          模板方法模式(Template Method Pattern)定義一個(gè)固定的算法框架,而將算法的一些步驟放到子類中實(shí)現(xiàn),使得子類可以在不改變算法框架的情況下重定義該算法的某些步驟。

          普通:
          @Repositorypublic class UserValue {    /** 值操作 */    @Resource(name = "stringRedisTemplate")    private ValueOperations<String, String> valueOperations;    /** 值模式 */    private static final String KEY_FORMAT = "Value:User:%s";
          /** 設(shè)置值 */ public void set(Long id, UserDO value) { String key = String.format(KEY_FORMAT, id); valueOperations.set(key, JSON.toJSONString(value)); }
          /** 獲取值 */ public UserDO get(Long id) { String key = String.format(KEY_FORMAT, id); String value = valueOperations.get(key); return JSON.parseObject(value, UserDO.class); }
          ...}
          @Repositorypublic class RoleValue { /** 值操作 */ @Resource(name = "stringRedisTemplate") private ValueOperations<String, String> valueOperations; /** 值模式 */ private static final String KEY_FORMAT = "Value:Role:%s";
          /** 設(shè)置值 */ public void set(Long id, RoleDO value) { String key = String.format(KEY_FORMAT, id); valueOperations.set(key, JSON.toJSONString(value)); }
          /** 獲取值 */ public RoleDO get(Long id) { String key = String.format(KEY_FORMAT, id); String value = valueOperations.get(key); return JSON.parseObject(value, RoleDO.class); }
          ...}

          精簡:
          public abstract class AbstractDynamicValue {    /** 值操作 */    @Resource(name = "stringRedisTemplate")    private ValueOperations valueOperations;
          /** 設(shè)置值 */ public void set(I id, V value) { valueOperations.set(getKey(id), JSON.toJSONString(value)); }
          /** 獲取值 */ public V get(I id) { return JSON.parseObject(valueOperations.get(getKey(id)), getValueClass()); }
          ...
          /** 獲取主鍵 */ protected abstract String getKey(I id);
          /** 獲取值類 */ protected abstract Class getValueClass();}
          @Repositorypublic class UserValue extends AbstractValue { /** 獲取主鍵 */ @Override protected String getKey(Long id) { return String.format("Value:User:%s", id); }
          /** 獲取值類 */ @Override protected Class getValueClass() { return UserDO.class; }}
          @Repositorypublic class RoleValue extends AbstractValue { /** 獲取主鍵 */ @Override protected String getKey(Long id) { return String.format("Value:Role:%s", id); }
          /** 獲取值類 */ @Override protected Class getValueClass() { return RoleDO.class; }}


          10.2.建造者模式



          建造者模式(Builder Pattern)將一個(gè)復(fù)雜對象的構(gòu)造與它的表示分離,使同樣的構(gòu)建過程可以創(chuàng)建不同的表示,這樣的設(shè)計(jì)模式被稱為建造者模式。

          普通:


          public interface DataHandler<T> {    /** 解析數(shù)據(jù) */public T parseData(Record record);
          /** 存儲(chǔ)數(shù)據(jù) */public boolean storeData(List dataList);}
          public long executeFetch(String tableName, int batchSize, DataHandler dataHandler) throws Exception { // 構(gòu)建下載會(huì)話 DownloadSession session = buildSession(tableName);
          // 獲取數(shù)據(jù)數(shù)量 long recordCount = session.getRecordCount(); if (recordCount == 0) { return 0; }
          // 進(jìn)行數(shù)據(jù)讀取 long fetchCount = 0L; try (RecordReader reader = session.openRecordReader(0L, recordCount, true)) { // 依次讀取數(shù)據(jù) Record record; List dataList = new ArrayList<>(batchSize); while ((record = reader.read()) != null) { // 解析添加數(shù)據(jù) T data = dataHandler.parseData(record); if (Objects.nonNull(data)) { dataList.add(data); }
          // 批量存儲(chǔ)數(shù)據(jù) if (dataList.size() == batchSize) { boolean isContinue = dataHandler.storeData(dataList); fetchCount += batchSize; dataList.clear(); if (!isContinue) { break; } } }
          // 存儲(chǔ)剩余數(shù)據(jù) if (CollectionUtils.isNotEmpty(dataList)) { dataHandler.storeData(dataList); fetchCount += dataList.size(); dataList.clear(); } }
          // 返回獲取數(shù)量 return fetchCount;}
          // 使用案例long fetchCount = odpsService.executeFetch("user", 5000, new DataHandler() { /** 解析數(shù)據(jù) */ @Overridepublic T parseData(Record record) { UserDO user = new UserDO(); user.setId(record.getBigint("id")); user.setName(record.getString("name")); return user; }
          /** 存儲(chǔ)數(shù)據(jù) */ @Overridepublic boolean storeData(List dataList) { userDAO.batchInsert(dataList); return true; }});



          精簡:


          public  long executeFetch(String tableName, int batchSize, Function dataParser, Function, Boolean> dataStorage) throws Exception {    // 構(gòu)建下載會(huì)話    DownloadSession session = buildSession(tableName);
          // 獲取數(shù)據(jù)數(shù)量 long recordCount = session.getRecordCount(); if (recordCount == 0) { return 0; }
          // 進(jìn)行數(shù)據(jù)讀取 long fetchCount = 0L; try (RecordReader reader = session.openRecordReader(0L, recordCount, true)) { // 依次讀取數(shù)據(jù) Record record; List dataList = new ArrayList<>(batchSize); while ((record = reader.read()) != null) { // 解析添加數(shù)據(jù) T data = dataParser.apply(record); if (Objects.nonNull(data)) { dataList.add(data); }
          // 批量存儲(chǔ)數(shù)據(jù) if (dataList.size() == batchSize) { Boolean isContinue = dataStorage.apply(dataList); fetchCount += batchSize; dataList.clear(); if (!Boolean.TRUE.equals(isContinue)) { break; } } }
          // 存儲(chǔ)剩余數(shù)據(jù) if (CollectionUtils.isNotEmpty(dataList)) { dataStorage.apply(dataList); fetchCount += dataList.size(); dataList.clear(); } }
          // 返回獲取數(shù)量 return fetchCount;}
          // 使用案例long fetchCount = odpsService.executeFetch("user", 5000, record -> { UserDO user = new UserDO(); user.setId(record.getBigint("id")); user.setName(record.getString("name")); return user; }, dataList -> { userDAO.batchInsert(dataList); return true; });



          普通的建造者模式,實(shí)現(xiàn)時(shí)需要定義 DataHandler 接口,調(diào)用時(shí)需要實(shí)現(xiàn) DataHandler 匿名內(nèi)部類,代碼較多較繁瑣。而精簡后的建造者模式,充分利用了函數(shù)式編程,實(shí)現(xiàn)時(shí)無需定義接口,直接使用 Function 接口;調(diào)用時(shí)無需實(shí)現(xiàn)匿名內(nèi)部類,直接采用 lambda 表達(dá)式,代碼較少較簡潔。


          10.3.代理模式



          Spring 中最重要的代理模式就是 AOP (Aspect-Oriented Programming,面向切面的編程),是使用 JDK 動(dòng)態(tài)代理和 CGLIB 動(dòng)態(tài)代理技術(shù)來實(shí)現(xiàn)的。

          普通:


          @Slf4j@RestController@RequestMapping("/user")public class UserController {    /** 用戶服務(wù) */    @Autowired    private UserService userService;
          /** 查詢用戶 */ @PostMapping("/queryUser") public Result queryUser(@RequestBody @Valid UserQueryVO query) { try { PageDataVO pageData = userService.queryUser(query); return Result.success(pageData); } catch (Exception e) { log.error(e.getMessage(), e); return Result.failure(e.getMessage()); } } ...}



          精簡1:

          基于? @ControllerAdvice 的異常處理:


          @RestController@RequestMapping("/user")public class UserController {    /** 用戶服務(wù) */    @Autowired    private UserService userService;
          /** 查詢用戶 */ @PostMapping("/queryUser") public Result> queryUser(@RequestBody @Valid UserQueryVO query) { PageDataVO pageData = userService.queryUser(query); return Result.success(pageData); } ...}
          @Slf4j@ControllerAdvicepublic class GlobalControllerAdvice { /** 處理異常 */ @ResponseBody @ExceptionHandler(Exception.class) public Result handleException(Exception e) { log.error(e.getMessage(), e); return Result.failure(e.getMessage()); }}



          精簡2:

          基于 AOP 的異常處理:


          // UserController代碼同"精簡1"
          @Slf4j@Aspectpublic class WebExceptionAspect { /** 點(diǎn)切面 */ @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") private void webPointcut() {}
          /** 處理異常 */ @AfterThrowing(pointcut = "webPointcut()", throwing = "e") public void handleException(Exception e) { Result result = Result.failure(e.getMessage()); writeContent(JSON.toJSONString(result)); } ...}





          11.利用刪除代碼





          “少即是多”,“少”不是空白而是精簡,“多”不是擁擠而是完美。刪除多余的代碼,才能使代碼更精簡更完美。




          11.1.刪除已廢棄的代碼



          刪除項(xiàng)目中的已廢棄的包、類、字段、方法、變量、常量、導(dǎo)入、注解、注釋、已注釋代碼、Maven包導(dǎo)入、MyBatis的SQL語句、屬性配置字段等,可以精簡項(xiàng)目代碼便于維護(hù)。

          普通:


          import lombok.extern.slf4j.Slf4j;@Slf4j@Servicepublic class ProductService {    @Value("discardRate")    private double discardRate;    ...    private ProductVO transProductDO(ProductDO productDO) {        ProductVO productVO = new ProductVO();        BeanUtils.copyProperties(productDO, productVO);        // productVO.setPrice(getDiscardPrice(productDO.getPrice()));        return productVO;    }    private BigDecimal getDiscardPrice(BigDecimal originalPrice) {        ...    }}



          精簡:
          @Servicepublic class ProductService {    ...    private ProductVO transProductDO(ProductDO productDO) {        ProductVO productVO = new ProductVO();        BeanUtils.copyProperties(productDO, productVO);        return productVO;    }}11.2.刪除接口方法的public對于接口(interface),所有的字段和方法都是public的,可以不用顯式聲明為public。普通:public interface UserDAO {    public Long countUser(@Param("query") UserQuery query);    public List queryUser(@Param("query") UserQuery query);}



          11.2.刪除接口方法的public



          對于接口(interface),所有的字段和方法都是 public 的,可以不用顯式聲明為 public 。

          普通:


          public interface UserDAO {    public Long countUser(@Param("query") UserQuery query);    public List queryUser(@Param("query") UserQuery query);}



          精簡:


          public interface UserDAO {    Long countUser(@Param("query") UserQuery query);    List queryUser(@Param("query") UserQuery query);}


          11.3.刪除枚舉構(gòu)造方法的 private



          對于枚舉(menu),構(gòu)造方法都是 private 的,可以不用顯式聲明為 private 。

          普通:



          public enum UserStatus {    DISABLED(0, "禁用"),    ENABLED(1, "啟用");  private final Integer value;    private final String desc;    private UserStatus(Integer value, String desc) {        this.value = value;        this.desc = desc;    }    ...}


          精簡:


          public enum UserStatus {    DISABLED(0, "禁用"),    ENABLED(1, "啟用");    private final Integer value;    private final String desc;    UserStatus(Integer value, String desc) {        this.value = value;        this.desc = desc;    }    ...}


          11.4.刪除 final 類方法的 final



          對于 final 類,不能被子類繼承,所以其方法不會(huì)被覆蓋,沒有必要添加 final 修飾。

          普通:


          public final Rectangle implements Shape {    ...    @Override    public final double getArea() {        return width * height;    }}



          精簡:


          public final Rectangle implements Shape {    ...    @Override    public double getArea() {        return width * height;    }}


          11.5.刪除基類 implements 的接口



          如果基類已 implements 某接口,子類沒有必要再 implements 該接口,只需要直接實(shí)現(xiàn)接口方法即可。

          普通:


          public interface Shape {    ...    double getArea();}public abstract AbstractShape implements Shape {    ...}public final Rectangle extends AbstractShape implements Shape {    ...    @Override    public double getArea() {        return width * height;    }}



          精簡:


          ...public final Rectangle extends AbstractShape {    ...    @Override    public double getArea() {        return width * height;    }}


          11.6.刪除不必要的變量



          不必要的變量,只會(huì)讓代碼看起來更繁瑣。

          普通:


          public Boolean existsUser(Long userId) {    Boolean exists = userDAO.exists(userId);    return exists;}



          精簡:


          public Boolean existsUser(Long userId) {    return userDAO.exists(userId);}





          后記





          古語又云:

          有道無術(shù),術(shù)尚可求也;有術(shù)無道,止于術(shù)。


          意思是:有“道”而無“術(shù)”,“術(shù)”還可以逐漸獲得;有“術(shù)”而無“道”,就可能止步于“術(shù)”了。所以,我們不要僅滿足于從實(shí)踐中總結(jié)“術(shù)”,因?yàn)椤暗馈钡谋憩F(xiàn)形式是多變的;而應(yīng)該上升到“道”的高度,因?yàn)椤靶g(shù)”背后的道理是相通的。當(dāng)遇到新的事物時(shí),我們可以從理論中找到“道”、從實(shí)踐中找出“術(shù)”,嘗試著去認(rèn)知新的事物。

          本文作者:


          陳昌毅,花名常意,地圖技術(shù)專家。


          推薦閱讀

          你要“老婆”不?谷歌程序員20行代碼送你一個(gè)!

          你猜一個(gè) TCP 連接上面能發(fā)多少個(gè) HTTP 請求?

          Spring 的 Controller 是單例還是多例?怎么保證并發(fā)的安全

          瀏覽 27
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲激情视频在线 | 777国产盗摄偷窥精品0000 | 无码中文字幕网 | 精品无码免费一区二区 | 美女操逼国产欧美亚洲色 |