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

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

    Check out the Cofoja project which provides contracts for Java through annotations. It provides Pre-/Postconditions and Invariants. Also in contrast to other Java implementations it correctly handles contracts defined in parent classes/interfaces. Contract evaluation can be enabled/disabled at runtime.

    Here is a code snippet from their tutorial:

    import com.google.java.contract.Invariant;
    import com.google.java.contract.Requires;
    
    @Invariant("size() >= 0")
    interface Stack {
      public int size();
    
      @Requires("size() >= 1")
      public T pop();
    
      public void push(T obj);
    }
    

提交回复
热议问题