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

后端 未结 8 2175
慢半拍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:33

    If I find myself repeating the same boiler-plate precondition checking code within a class, I refactor my code to reduce the duplication and to increase abstraction by extractung the repeated code into a new (static private) method. I use the Java-7 Objects.requireNonNull method for null checks.

提交回复
热议问题