我爱编程

Guava——Preconditions

2018-04-04  本文已影响17人  jiangmo

概述

Guava provides a number of precondition checking utilities. We strongly recommend importing these statically.

Each method has three variants:

Note: checkNotNull, checkArgument and checkState have a large number of overloads taking combinations of primitive and Object parameters rather than a varargs array — this allows calls such as those above to avoid both primitive boxing and varags array allocation in the vast majority of cases.

使用建议

We recommend that you split up preconditions into distinct lines, which can help you figure out which precondition failed while debugging. Additionally, you should provide helpful error messages, which is easier when each check is on its own line.

We preferred rolling our own preconditions checks over e.g. the comparable utilities from Apache Commons for a few reasons. Briefly:

实例

public static void testPreconditions(){
        // ====都是快速失败,直接抛出异常
        Integer i1 = 2;
        // 检查参数
        Preconditions.checkArgument(i1>1);
        Preconditions.checkArgument(i1>1, "ok");

        String s1 = "s1";
        // 是否空
        s1 = Preconditions.checkNotNull(s1, "%s is null", s1);

        // Ensures the truth of an expression involving the state of the calling instance
        Preconditions.checkState(s1 != null);

        List<Integer> list1 = Arrays.asList(1, 2, 3,4);
        // 检查元素index是否越界
        Preconditions.checkElementIndex(2, list1.size());
        // 检查position是否越界
        Preconditions.checkPositionIndex(1, list1.size());
        // 检查[start, end]是否越界
        Preconditions.checkPositionIndexes(1, 3, list1.size());
    }

Ref:
https://github.com/google/guava/wiki/PreconditionsExplained

上一篇 下一篇

猜你喜欢

热点阅读