2024/3/4

Guava Basic Preconditions

Guava 是 Google 開發的 Java 開源工具 Library。內容主要有兩個部分:擴充 Java Collection Framework,提供更好用的 function,例如cache, range,以及 hash function

使用 Guava 只需要在 maven pom.xml 直接加入 dependency 即可

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>32.1.2-jre</version>
  <!-- or, for Android: -->
  <!-- <version>32.1.2-android</version> -->
</dependency>

基本工具

Null Check

JDK 跟 Guava 都有針對 null check 問題提供了 Optional 類別來解決

Optional,Gauva工具及和Java8中实现的区别_Tonels的博客-CSDN博客

java.util.Optional 是 final 的類別,無法被繼承

com.google.common.base.Optional 是 abstract class,有實作 Serializable

兩種 Optional 基本的使用方式差不多

        com.google.common.base.Optional<Integer> possible = com.google.common.base.Optional.of(5);
        boolean isPresent = possible.isPresent(); // returns true
//        int val = possible.get(); // returns 5
        int val = possible.or(-1); // returns 5
        System.out.printf("isPresent=%b, val=%d%n", isPresent, val);

        com.google.common.base.Optional<Integer> possible2 = com.google.common.base.Optional.fromNullable(null);
        isPresent = possible2.isPresent();
        val = possible2.or(-1);
        System.out.printf("isPresent=%b, val=%d%n", isPresent, val);

        java.util.Optional<Integer> opt = java.util.Optional.of(5);
        boolean isPresent2 = opt.isPresent();
//        int val2 = opt.get();
        int val2 = opt.orElse(-1);
        System.out.printf("isPresent2=%b, val2=%d%n", isPresent2, val2);

        java.util.Optional<Integer> opt2 = java.util.Optional.ofNullable(null);
        isPresent2 = opt2.isPresent();
        val2 = opt2.orElse(-1);
        System.out.printf("isPresent2=%b, val2=%d%n", isPresent2, val2);

Preconditions

有很多 static method 可檢查 method 或 constructor 是否有正確的參數數值,如果檢查結果失敗,就會 throw exception

每一種 Preconditions 的 static method 都有三種變化

  1. No arguments,exception 裡面沒有 error message

  2. 有一個 Object argument,作為 error message,丟出的 exception 裡面會有 error message

  3. 有一個 String argument,搭配任意數量的 Object arguments,作為 error message 的 placeholder,類似 printf

Preconditions 的 checkArgument 可檢查參數的正確性,失敗時會丟出 IllegalArgumentException

沒有 error messge

    @Test
    public void checkArgument_without_error_message() {
        int age = -18;

        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            Preconditions.checkArgument(age > 0);
        });

//        String expectedMessage = null;
        String actualMessage = exception.getMessage();
        assertNull(actualMessage);
    }

有 error message

    @Test
    public void checkArgument_with_error_message() {
        int age = -18;
        String message = "Age can't be zero or less than zero.";

        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            Preconditions.checkArgument(age > 0, message);
        });

        String expectedMessage = message;
        String actualMessage = exception.getMessage();
        assertEquals(expectedMessage, actualMessage);
    }

有 error message template

    @Test
    public void checkArgument_with_template_error_message() {
        int age = -18;
        String message = "Age should be positive number, you supplied %s.";

        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            Preconditions.checkArgument(age > 0, message, age);
        });

        String expectedMessage = String.format(message, age);
        String actualMessage = exception.getMessage();
        assertEquals(expectedMessage, actualMessage);;
    }

checkElementIndex

    @Test
    public void checkElementIndex() {
        int[] numbers = { 1, 2, 3, 4, 5 };
        String message = "Please check the bound of an array and retry";

        Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> {
            Preconditions.checkElementIndex(6, numbers.length - 1, message);
        });

//        expectedMessage: Please check the bound of an array and retry (6) must be less than size (4)
        String expectedMessage = String.format(message+" (%d) must be less than size (%d)", 6, numbers.length - 1);
//        System.out.printf("expectedMessage=%s%n", expectedMessage);
        String actualMessage = exception.getMessage();
        assertEquals(expectedMessage, actualMessage);;
    }

checkNotNull

    @Test
    public void checkNotNull () {
        String nullObject = null;
        String message = "Please check the Object supplied, its null!";

        Exception exception = assertThrows(NullPointerException.class, () -> {
            Preconditions.checkNotNull(nullObject, message);
        });

        String expectedMessage = message;
//        System.out.printf("expectedMessage=%s%n", expectedMessage);
        String actualMessage = exception.getMessage();
        assertEquals(expectedMessage, actualMessage);;
    }

checkPositionIndex

    @Test
    public void checkPositionIndex() {
        int[] numbers = { 1, 2, 3, 4, 5 };
        String message = "Please check the bound of an array and retry";

        Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> {
            Preconditions.checkPositionIndex(6, numbers.length - 1, message);
        });

//        expectedMessage: Please check the bound of an array and retry (6) must not be greater than size (4)
        String expectedMessage = String.format(message+" (%d) must not be greater than size (%d)", 6, numbers.length - 1);
//        System.out.printf("expectedMessage=%s%n", expectedMessage);
        String actualMessage = exception.getMessage();
        assertEquals(expectedMessage, actualMessage);;
    }

checkState

    @Test
    public void checkState() {
        int[] validStates = { -1, 0, 1 };
        int givenState = 10;
        String message = "You have entered an invalid state";

        Exception exception = assertThrows(IllegalStateException.class, () -> {
            Preconditions.checkState(
                    Arrays.binarySearch(validStates, givenState) > 0, message);
        });

        String expectedMessage = message;
        String actualMessage = exception.getMessage();
        assertEquals(expectedMessage, actualMessage);;
    }

References

Home · google/guava Wiki · GitHub

Guava Guide | Baeldung

Guava:Google开源的Java工具库,太强大了 | Java程序员进阶之路

Google Guava 工具類 的介紹和使用 - HackMD

# Google Guava官方教程

專欄文章:Guava 教學

沒有留言:

張貼留言