天天看點

Java代碼精簡之道

前言

古語有雲:

道為術之靈,術為道之體;以道統術,以術得道。

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

在拜讀大佬“孤盡”的文章《

Code Review是苦澀但有意思的修行

》時,感受最深的一句話就是:“優質的代碼一定是少即是多的精兵原則”,這就是大佬的代碼精簡之“道”。

工匠追求“術”到極緻,其實就是在尋“道”,且離悟“道”也就不遠了,亦或是已經得道,這就是“工匠精神”——一種追求“以術得道”的精神。如果一個工匠隻滿足于“術”,不能追求“術”到極緻去悟“道”,那隻是一個靠“術”養家糊口的工匠而已。作者根據多年來的實踐探索,總結了大量的Java代碼精簡之“術”,試圖闡述出心中的Java代碼精簡之“道”。

1.利用文法

1.1.利用三元表達式

普通:

String title;
if (isMember(phone)) {
    title = "會員";
} else {
    title = "遊客";
}           

精簡:

String title = isMember(phone) ? "會員" : "遊客";           

注意:對于包裝類型的算術計算,需要注意避免拆包時的空指針問題。

1.2.利用for-each語句

從Java 5起,提供了for-each循環,簡化了數組和集合的循環周遊。for-each循環允許你無需保持傳統for循環中的索引就可以周遊數組,或在使用疊代器時無需在while循環中調用hasNext方法和next方法就可以周遊集合。

double[] values = ...;
for(int i = 0; i < values.length; i++) {
    double value = values[i];
    // TODO: 處理value
}

List<Double> valueList = ...;
Iterator<Double> iterator = valueList.iterator();
while (iterator.hasNext()) {
    Double value = iterator.next();
    // TODO: 處理value
}           
double[] values = ...;
for(double value : values) {
    // TODO: 處理value
}

List<Double> valueList = ...;
for(Double value : valueList) {
    // TODO: 處理value
}           

1.3.利用try-with-resource語句

所有實作Closeable接口的“資源”,均可采用try-with-resource進行簡化。

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("關閉檔案異常", 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關鍵字

利用return關鍵字,可以提前函數傳回,避免定義中間變量。

public static boolean hasSuper(@NonNull List<UserDO> 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<UserDO> userList) {
    for (UserDO user : userList) {
        if (Boolean.TRUE.equals(user.getIsSuper())) {
            return true;
        }
    }
    return false;
}           

1.5.利用static關鍵字

利用static關鍵字,可以把字段變成靜态字段,也可以把函數變為靜态函數,調用時就無需初始化類對象。

public final class GisHelper {
    public double distance(double lng1, double lat1, double lng2, double lat2) {
        // 方法實作代碼
    }
}

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) {
        // 方法實作代碼
    }
}

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

1.6.利用lambda表達式

Java 8釋出以後,lambda表達式大量替代匿名内部類的使用,在簡化了代碼的同時,更突出了原有匿名内部類中真正有用的那部分代碼。

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

1.7.利用方法引用

方法引用(::),可以簡化lambda表達式,省略變量聲明和函數調用。

Arrays.sort(nameArray, (a, b) -> a.compareToIgnoreCase(b));
List<Long> userIdList = userList.stream()
    .map(user -> user.getId())
    .collect(Collectors.toList());           
Arrays.sort(nameArray, String::compareToIgnoreCase);
List<Long> userIdList = userList.stream()
    .map(UserDO::getId)
    .collect(Collectors.toList());           

1.8.利用靜态導入

靜态導入(import static),當程式中大量使用同一靜态常量和函數時,可以簡化靜态常量和函數的引用。

List<Double> 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<Double> areaList = radiusList.stream().map(r -> PI * pow(r, 2)).collect(toList());
...           

注意:靜态引入容易造成代碼閱讀困難,是以在實際項目中應該警慎使用。

1.9.利用unchecked異常

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

@Service
public 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("使用者無操作權限");
        }
        ...
    }
    ...
}

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/createUser")
    public Result<Void> createUser(@RequestBody @Valid UserCreateVO create, OpUserVO user) throws BusinessException {
        userService.createUser(create, user);
        return Result.success();
    }
    ...
}           
@Service
public class UserService {
    public void createUser(UserCreateVO create, OpUserVO user) {
        checkOperatorUser(user);
        ...
    }
    private void checkOperatorUser(OpUserVO user) {
        if (!hasPermission(user)) {
            throw new BusinessRuntimeException("使用者無操作權限");
        }
        ...
    }
    ...
}

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/createUser")
    public Result<Void> 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
@ToString
public class UserVO {
    private Long id;
    private String name;
    ...
}           

2.2.利用Validation注解

@Getter
@Setter
@ToString
public class UserCreateVO {
    private String name;
    private Long companyId;
}

@Service
public class UserService {
    public Long createUser(UserCreateVO create) {
        // 驗證參數
        if (StringUtils.isBlank(create.getName())) {
            throw new IllegalArgumentException("使用者名稱不能為空");
        }
        if (Objects.isNull(create.getCompanyId())) {
            throw new IllegalArgumentException("公司辨別不能為空");
        }

        // TODO: 建立使用者
        return null;
    }
}           
@Getter
@Setter
@ToString
public class UserCreateVO {
    @NotBlank(message = "使用者名稱不能為空")
    private String name;
    @NotNull(message = "公司辨別不能為空")
    private Long companyId;
    ...
}

@Service
@Validated
public class UserService {
    public Long createUser(@Valid UserCreateVO create) {
        // TODO: 建立使用者
        return null;
    }
}           

2.3.利用@NonNull注解

Spring的@NonNull注解,用于标注參數或傳回值非空,适用于項目内部團隊協作。隻要實作方和調用方遵循規範,可以避免不必要的空值判斷,這充分展現了阿裡的“新六脈神劍”提倡的“因為信任,是以簡單”。

public List<UserVO> queryCompanyUser(Long companyId) {
    // 檢查公司辨別
    if (companyId == null) {
        return null;
    }

    // 查詢傳回使用者
    List<UserDO> userList = userDAO.queryByCompanyId(companyId);
    return userList.stream().map(this::transUser).collect(Collectors.toList());
}

Long companyId = 1L;
List<UserVO> userList = queryCompanyUser(companyId);
if (CollectionUtils.isNotEmpty(userList)) {
    for (UserVO user : userList) {
        // TODO: 處理公司使用者
    }
}           
public @NonNull List<UserVO> queryCompanyUser(@NonNull Long companyId) {
    List<UserDO> userList = userDAO.queryByCompanyId(companyId);
    return userList.stream().map(this::transUser).collect(Collectors.toList());
}

Long companyId = 1L;
List<UserVO> userList = queryCompanyUser(companyId);
for (UserVO user : userList) {
    // TODO: 處理公司使用者
}           

2.4.利用注解特性

注解有以下特性可用于精簡注解聲明:

  1. 當注解屬性值跟預設值一緻時,可以删除該屬性指派;
  2. 當注解隻有value屬性時,可以去掉value進行簡寫;
  3. 當注解屬性組合等于另一個特定注解時,直接采用該特定注解。
@Lazy(true);
@Service(value = "userService")
@RequestMapping(path = "/getUser", method = RequestMethod.GET)           
@Lazy
@Service("userService")
@GetMapping("/getUser")           

3.利用泛型

3.1.泛型接口

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

public interface Comparable {
    public int compareTo(Object other);
}

@Getter
@Setter
@ToString
public 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<T> {
    public int compareTo(T other);
}

@Getter
@Setter
@ToString
public class UserVO implements Comparable<UserVO> {
    private Long id;

    @Override
    public int compareTo(UserVO other) {
        return Long.compare(this.id, other.id);
    }
}           

3.2.泛型類

@Getter
@Setter
@ToString
public class IntPoint {
    private Integer x;
    private Integer y;
}

@Getter
@Setter
@ToString
public class DoublePoint {
    private Double x;
    private Double y;
}           
@Getter
@Setter
@ToString
public class Point<T extends Number> {
    private T x;
    private T y;
}           

3.3.泛型方法

public static Map<String, Integer> newHashMap(String[] keys, Integer[] values) {
    // 檢查參數非空
    if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {
        return Collections.emptyMap();
    }

    // 轉化哈希映射
    Map<String, Integer> 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 <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {
    // 檢查參數非空
    if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {
        return Collections.emptyMap();
    }

    // 轉化哈希映射
    Map<K, V> 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.利用構造方法

構造方法,可以簡化對象的初始化和設定屬性操作。對于屬性字段較少的類,可以自定義構造方法。

@Getter
@Setter
@ToString
public class PageDataVO<T> {
    private Long totalCount;
    private List<T> dataList;
}

PageDataVO<UserVO> pageData = new PageDataVO<>();
pageData.setTotalCount(totalCount);
pageData.setDataList(userList);
return pageData;           
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class PageDataVO<T> {
    private Long totalCount;
    private List<T> dataList;
}

return new PageDataVO<>(totalCount, userList);           

注意:如果屬性字段被替換時,存在構造函數初始化指派問題。比如把屬性字段title替換為nickname,由于構造函數的參數個數和類型不變,原有構造函數初始化語句不會報錯,導緻把原title值指派給nickname。如果采用Setter方法指派,編譯器會提示錯誤并要求修複。

4.2.利用Set的add方法

利用Set的add方法的傳回值,可以直接知道該值是否已經存在,可以避免調用contains方法判斷存在。

以下案例是進行使用者去重轉化操作,需要先調用contains方法判斷存在,後調用add方法進行添加。

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

4.3.利用Map的computeIfAbsent方法

利用Map的computeIfAbsent方法,可以保證擷取到的對象非空,進而避免了不必要的空判斷和重新設定值。

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

4.4.利用鍊式程式設計

鍊式程式設計,也叫級聯式程式設計,調用對象的函數時傳回一個this對象指向對象本身,達到鍊式效果,可以級聯調用。鍊式程式設計的優點是:程式設計性強、可讀性強、代碼簡潔。

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<String> ANIMAL_LIST;
static {
    List<String> animalList = new ArrayList<>();
    animalList.add("dog");
    animalList.add("cat");
    animalList.add("tiger");
    ANIMAL_LIST = Collections.unmodifiableList(animalList);
}           
// JDK流派
public static final List<String> ANIMAL_LIST = Arrays.asList("dog", "cat", "tiger");
// Guava流派
public static final List<String> ANIMAL_LIST = ImmutableList.of("dog", "cat", "tiger");           

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

5.4.簡化資料拷貝

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<UserVO> userVOList = JSON.parseArray(JSON.toJSONString(userDOList), UserVO.class);           

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

5.5.簡化異常斷言

if (Objects.isNull(userId)) {
    throw new IllegalArgumentException("使用者辨別不能為空");
}           
Assert.notNull(userId, "使用者辨別不能為空");           

注意:可能有些插件不認同這種判斷,導緻使用該對象時會有空指針警告。

5.6.簡化測試用例

把測試用例資料以JSON格式存入檔案中,通過JSON的parseObject和parseArray方法解析成對象。雖然執行效率上有所下降,但可以減少大量的指派語句,進而精簡了測試代碼。

@Test
public void testCreateUser() {
    UserCreateVO userCreate = new UserCreateVO();
    userCreate.setName("Changyi");
    userCreate.setTitle("Developer");
    userCreate.setCompany("AMAP");
    ...
    Long userId  = userService.createUser(OPERATOR, userCreate);
    Assert.assertNotNull(userId, "建立使用者失敗");
}           
@Test
public 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, "建立使用者失敗");
}           

建議:JSON檔案名最好以被測試的方法命名,如果有多個版本可以用數字字尾表示。

5.7.簡化算法實作

一些正常算法,已有現成的工具方法,我們就沒有必要自己實作了。

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

5.8.封裝工具方法

一些特殊算法,沒有現成的工具方法,我們就隻好自己親自實作了。

比如,SQL設定參數值的方法就比較難用,setLong方法不能設定參數值為null。

/** 設定參數值 */
if (Objects.nonNull(user.getId())) {
    statement.setLong(1, user.getId());
} else {
    statement.setNull(1, Types.BIGINT);
}
...           

我們可以封裝為一個工具類SqlHelper,簡化設定參數值的代碼。

/** SQL輔助類 */
public final class SqlHelper {
    /** 設定長整數值 */
    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);
        }
    }
    ...
}

/** 設定參數值 */
SqlHelper.setLong(statement, 1, user.getId());           

6.利用資料結構

6.1.利用數組簡化

對于固定上下限範圍的if-else語句,可以用數組+循環來簡化。

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;
}           

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

6.2.利用Map簡化

對于映射關系的if-else語句,可以用Map來簡化。此外,此規則同樣适用于簡化映射關系的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<String, String> BIOLOGY_CLASS_MAP
    = ImmutableMap.<String, String>builder()
        .put("dog", "animal")
        .put("cat", "animal")
        .put("lavender", "plant")
        ...
        .build();
public static String getBiologyClass(String name) {
    return BIOLOGY_CLASS_MAP.get(name);
}           

已經把方法簡化為一行代碼,其實都沒有封裝方法的必要了。

6.3.利用容器類簡化

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

@Setter
@Getter
@ToString
@AllArgsConstructor
public static class PointAndDistance {
    private Point point;
    private Double distance;
}

public static PointAndDistance getNearest(Point point, Point[] points) {
    // 計算最近點和距離
    ...

    // 傳回最近點和距離
    return new PointAndDistance(nearestPoint, nearestDistance);
}           
public static Pair<Point, Double> getNearest(Point point, Point[] points) {
    // 計算最近點和距離
    ...

    // 傳回最近點和距離
    return ImmutablePair.of(nearestPoint, nearestDistance);
}           

6.4.利用ThreadLocal簡化

ThreadLocal提供了線程專有對象,可以在整個線程生命周期中随時取用,極大地友善了一些邏輯的實作。用ThreadLocal儲存線程上下文對象,可以避免不必要的參數傳遞。

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

public static String formatDate(Date date, DateFormat format) {
    return format.format(date);
}

public static List<String> getDateList(Date minDate, Date maxDate, DateFormat format) {
    List<String> 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;
}           

可能你會覺得以下的代碼量反而多了,如果調用工具方法的地方比較多,就可以省下一大堆DateFormat初始化和傳入參數的代碼。

private static final ThreadLocal<DateFormat> LOCAL_DATE_FORMAT = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public static String formatDate(Date date) {
    return LOCAL_DATE_FORMAT.get().format(date);
}

public static List<String> getDateList(Date minDate, Date maxDate) {
    List<String> 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有一定的記憶體洩露的風險,盡量在業務代碼結束前調用remove方法進行資料清除。

7.利用Optional

在Java 8裡,引入了一個Optional類,該類是一個可以為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();
        }
    }
}           
String zipcode = Optional.ofNullable(user).map(User::getAddress)
    .map(Address::getCountry).map(Country::getZipcode).orElse(null);           

8.利用Stream

流(Stream)是Java 8的新成員,允許你以聲明式處理資料集合,可以看成為一個周遊資料集的進階疊代器。流主要有三部分構成:擷取一個資料源→資料轉換→執行操作擷取想要的結果。每次轉換原有 Stream 對象不改變,傳回一個新的 Stream 對象,這就允許對其操作可以像鍊條一樣排列,形成了一個管道。流(Stream)提供的功能非常有用,主要包括比對、過濾、彙總、轉化、分組、分組彙總等功能。

8.1.比對集合資料

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.過濾集合資料

List<UserDO> resultList = new ArrayList<>();
for (UserDO user : userList) {
    if (Boolean.TRUE.equals(user.getIsSuper())) {
        resultList.add(user);
    }
}           
List<UserDO> resultList = userList.stream()
    .filter(user -> Boolean.TRUE.equals(user.getIsSuper()))
    .collect(Collectors.toList());           

8.3.彙總集合資料

double total = 0.0D;
for (Account account : accountList) {
    total += account.getBalance();
}           
double total = accountList.stream().mapToDouble(Account::getBalance).sum();           

8.4.轉化集合資料

List<UserVO> userVOList = new ArrayList<>();
for (UserDO userDO : userDOList) {
    userVOList.add(transUser(userDO));
}           
List<UserVO> userVOList = userDOList.stream()
    .map(this::transUser).collect(Collectors.toList());           

8.5.分組集合資料

Map<Long, List<UserDO>> roleUserMap = new HashMap<>();
for (UserDO userDO : userDOList) {
    roleUserMap.computeIfAbsent(userDO.getRoleId(), key -> new ArrayList<>())
        .add(userDO);
}           
Map<Long, List<UserDO>> roleUserMap = userDOList.stream()
    .collect(Collectors.groupingBy(UserDO::getRoleId));           

8.6.分組彙總集合

Map<Long, Double> 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.利用程式結構

9.1.傳回條件表達式

條件表達式判斷傳回布爾值,條件表達式本身就是結果。

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 = "上報工作日報成功";
    dingtalkService.sendMessage(user.getPhone(), message);
} else {
    String message = "上報工作日報失敗:" + result.getMessage();
    log.warn(message);
    dingtalkService.sendMessage(user.getPhone(), message);
}           
String message;
Result result = summaryService.reportWorkDaily(workDaily);
if (result.isSuccess()) {
    message = "上報工作日報成功";
} else {
    message = "上報工作日報失敗:" + result.getMessage();
    log.warn(message);
}
dingtalkService.sendMessage(user.getPhone(), message);           

9.3.調整表達式位置

調整表達式位置,在邏輯不變的前提下,讓代碼變得更簡潔。

普通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())) {
    ... // 處理邏輯代碼
}           

注意:有些規範可能不建議這種精簡寫法。

9.4.利用非空對象

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

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.利用設計模式

10.1.模闆方法模式

模闆方法模式(Template Method Pattern)定義一個固定的算法架構,而将算法的一些步驟放到子類中實作,使得子類可以在不改變算法架構的情況下重定義該算法的某些步驟。

@Repository
public class UserValue {
    /** 值操作 */
    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> valueOperations;
    /** 值模式 */
    private static final String KEY_FORMAT = "Value:User:%s";

    /** 設定值 */
    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);
    }

    ...
}

@Repository
public class RoleValue {
    /** 值操作 */
    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> valueOperations;
    /** 值模式 */
    private static final String KEY_FORMAT = "Value:Role:%s";

    /** 設定值 */
    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<I, V> {
    /** 值操作 */
    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> valueOperations;

    /** 設定值 */
    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<V> getValueClass();
}

@Repository
public class UserValue extends AbstractValue<Long, UserDO> {
    /** 擷取主鍵 */
    @Override
    protected String getKey(Long id) {
        return String.format("Value:User:%s", id);
    }

    /** 擷取值類 */
    @Override
    protected Class<UserDO> getValueClass() {
        return UserDO.class;
    }
}

@Repository
public class RoleValue extends AbstractValue<Long, RoleDO> {
    /** 擷取主鍵 */
    @Override
    protected String getKey(Long id) {
        return String.format("Value:Role:%s", id);
    }

    /** 擷取值類 */
    @Override
    protected Class<RoleDO> getValueClass() {
        return RoleDO.class;
    }
}           

10.2.建造者模式

建造者模式(Builder Pattern)将一個複雜對象的構造與它的表示分離,使同樣的建構過程可以建立不同的表示,這樣的設計模式被稱為建造者模式。

public interface DataHandler<T> {
    /** 解析資料 */
    public T parseData(Record record);
    
    /** 存儲資料 */
    public boolean storeData(List<T> dataList);
}

public <T> long executeFetch(String tableName, int batchSize, DataHandler<T> dataHandler) throws Exception {
    // 建構下載下傳會話
    DownloadSession session = buildSession(tableName);

    // 擷取資料數量
    long recordCount = session.getRecordCount();
    if (recordCount == 0) {
        return 0;
    }

    // 進行資料讀取
    long fetchCount = 0L;
    try (RecordReader reader = session.openRecordReader(0L, recordCount, true)) {
        // 依次讀取資料
        Record record;
        List<T> dataList = new ArrayList<>(batchSize);
        while ((record = reader.read()) != null) {
            // 解析添加資料
            T data = dataHandler.parseData(record);
            if (Objects.nonNull(data)) {
                dataList.add(data);
            }

            // 批量存儲資料
            if (dataList.size() == batchSize) {
                boolean isContinue = dataHandler.storeData(dataList);
                fetchCount += batchSize;
                dataList.clear();
                if (!isContinue) {
                    break;
                }
            }
        }

        // 存儲剩餘資料
        if (CollectionUtils.isNotEmpty(dataList)) {
            dataHandler.storeData(dataList);
            fetchCount += dataList.size();
            dataList.clear();
        }
    }

    // 傳回擷取數量
    return fetchCount;
}

/** 使用案例 */
long fetchCount = odpsService.executeFetch("user", 5000, new DataHandler() {
    /** 解析資料 */
    @Override
    public T parseData(Record record) {
        UserDO user = new UserDO();
        user.setId(record.getBigint("id"));
        user.setName(record.getString("name"));
        return user;
    }
    
    /** 存儲資料 */
    @Override
    public boolean storeData(List<T> dataList) {
        userDAO.batchInsert(dataList);
        return true;
    }
});           
public <T> long executeFetch(String tableName, int batchSize, Function<Record, T> dataParser, Function<List<T>, Boolean> dataStorage) throws Exception {
    // 建構下載下傳會話
    DownloadSession session = buildSession(tableName);

    // 擷取資料數量
    long recordCount = session.getRecordCount();
    if (recordCount == 0) {
        return 0;
    }

    // 進行資料讀取
    long fetchCount = 0L;
    try (RecordReader reader = session.openRecordReader(0L, recordCount, true)) {
        // 依次讀取資料
        Record record;
        List<T> dataList = new ArrayList<>(batchSize);
        while ((record = reader.read()) != null) {
            // 解析添加資料
            T data = dataParser.apply(record);
            if (Objects.nonNull(data)) {
                dataList.add(data);
            }

            // 批量存儲資料
            if (dataList.size() == batchSize) {
                Boolean isContinue = dataStorage.apply(dataList);
                fetchCount += batchSize;
                dataList.clear();
                if (!Boolean.TRUE.equals(isContinue)) {
                    break;
                }
            }
        }

        // 存儲剩餘資料
        if (CollectionUtils.isNotEmpty(dataList)) {
            dataStorage.apply(dataList);
            fetchCount += dataList.size();
            dataList.clear();
        }
    }

    // 傳回擷取數量
    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;
    });           

普通的建造者模式,實作時需要定義DataHandler接口,調用時需要實作DataHandler匿名内部類,代碼較多較繁瑣。而精簡後的建造者模式,充分利用了函數式程式設計,實作時無需定義接口,直接使用Function接口;調用時無需實作匿名内部類,直接采用lambda表達式,代碼較少較簡潔。

10.3.代理模式

Spring中最重要的代理模式就是AOP(Aspect-Oriented Programming,面向切面的程式設計),是使用JDK動态代理和CGLIB動态代理技術來實作的。

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    /** 使用者服務 */
    @Autowired
    private UserService userService;

    /** 查詢使用者 */
    @PostMapping("/queryUser")
    public Result<?> queryUser(@RequestBody @Valid UserQueryVO query) {
        try {
            PageDataVO<UserVO> 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 {
    /** 使用者服務 */
    @Autowired
    private UserService userService;

    /** 查詢使用者 */
    @PostMapping("/queryUser")
    public Result<PageDataVO<UserVO>> queryUser(@RequestBody @Valid UserQueryVO query) {
        PageDataVO<UserVO> pageData = userService.queryUser(query);
        return Result.success(pageData);
    }
    ...
}

@Slf4j
@ControllerAdvice
public class GlobalControllerAdvice {
    /** 處理異常 */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.failure(e.getMessage());
    }
}           

精簡2:

基于AOP的異常處理:

// UserController代碼同"精簡1"

@Slf4j
@Aspect
public class WebExceptionAspect {
    /** 點切面 */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    private void webPointcut() {}

    /** 處理異常 */
    @AfterThrowing(pointcut = "webPointcut()", throwing = "e")
    public void handleException(Exception e) {
        Result<Void> result = Result.failure(e.getMessage());
        writeContent(JSON.toJSONString(result));
    }
    ...
}           

11.利用删除代碼

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

11.1.删除已廢棄的代碼

删除項目中的已廢棄的包、類、字段、方法、變量、常量、導入、注解、注釋、已注釋代碼、Maven包導入、MyBatis的SQL語句、屬性配置字段等,可以精簡項目代碼便于維護。

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public 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) {
        ...
    }
}           
@Service
public 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<UserDO> queryUser(@Param("query") UserQuery query);
}           
public interface UserDAO {
    Long countUser(@Param("query") UserQuery query);
    List<UserDO> queryUser(@Param("query") UserQuery query);
}           

11.3.删除枚舉構造方法的private

對于枚舉(menu),構造方法都是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類,不能被子類繼承,是以其方法不會被覆寫,沒有必要添加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該接口,隻需要直接實作接口方法即可。

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.删除不必要的變量

不必要的變量,隻會讓代碼看起來更繁瑣。

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

後記

古語又雲:

有道無術,術尚可求也;有術無道,止于術。

意思是:有“道”而無“術”,“術”還可以逐漸獲得;有“術”而無“道”,就可能止步于“術”了。是以,我們不要僅滿足于從實踐中總結“術”,因為“道”的表現形式是多變的;而應該上升到“道”的高度,因為“術”背後的道理是相通的。當遇到新的事物時,我們可以從理論中找到“道”、從實踐中找出“術”,嘗試着去認知新的事物。

作者資訊:陳昌毅,花名常意,地圖技術專家。