Is there an beautiful way to assert pre-conditions in Java methods?

后端 未结 8 2044
慢半拍i
慢半拍i 2021-01-02 02:08

A lot of my functions have a whole load of validation code just below the declarations:

if ( ! (start < end) ) {
    throw new IllegalStateException( \"S         


        
相关标签:
8条回答
  • 2021-01-02 02:44

    You might be able to do this with annotation and aspect orientated programming.

    I would use IllegalArgumentException if an argument combination is not legal. I would use IllegalStateException is in a state which prevents the method from working.

    You can create a helper method for the exception.

    public static void check(boolean test, String message) {
        if(!test) throw new IllegalArgumentException(message);
    }
    
    check(start < end, "Start must be before end.");
    
    0 讨论(0)
  • 2021-01-02 02:46

    Guava's Preconditions class is just for this. You typically use it with static imports, so your example would look like:

    checkArgument(start < end, "Start must be before end");
    

    It makes it easy to add more information to the message as well, without paying the cost of String concatenation if the check passes.

    checkArgument(start < end, "Start (%s) must be before end (%s)", start, end);
    

    Unlike assert statements, these can't be disabled.

    0 讨论(0)
提交回复
热议问题