美文网首页我爱编程
Guava——Preconditions

Guava——Preconditions

作者: jiangmo | 来源:发表于2018-04-04 10:57 被阅读17次

    概述

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

    Each method has three variants:

    • No extra arguments. Any exceptions are thrown without error messages.
    • An extra Object argument. Any exception is thrown with the error message object.toString().
    • An extra String argument, with an arbitrary number of additional Object arguments. This behaves something like printf, but for GWT compatibility and efficiency, it only allows %s indicators.

    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:

    • After static imports, the Guava methods are clear and unambiguous. checkNotNull makes it clear what is being done, and what exception will be thrown.
    • checkNotNull returns its argument after validation, allowing simple one-liners in constructors: this.field = checkNotNull(field);.
    • Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use checkNotNull over Objects.requireNonNull)

    实例

    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

    相关文章

      网友评论

        本文标题:Guava——Preconditions

        本文链接:https://www.haomeiwen.com/subject/zizhhftx.html