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

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

    Aspect oriented programming can be used for such a problem. Method calls can be intercepted checking for the invariant. Pointcuts and advices are configured in a declarative way. Spring and Guice make usage of AOP straightforward.

    Here's an example in Guice.

提交回复
热议问题