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

后端 未结 8 2043
慢半拍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.

    0 讨论(0)
  • 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<T> {
      public int size();
    
      @Requires("size() >= 1")
      public T pop();
    
      public void push(T obj);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-02 02:39

    For input validation, you can also use Apache Commons Validator.

    Note that input validation should always be enabled. Hence it is conceptually very different from assertion checking (as, e.g., in Eiffel), which can be optionally on/off -- see the answer to this related stack overflow question When should I use Apache Commons' Validate.isTrue, and when should I just use the 'assert' keyword?

    0 讨论(0)
  • 2021-01-02 02:39

    The JUnit package has constructs like assert that would aid in doing such condition check.

    0 讨论(0)
  • 2021-01-02 02:41

    How about assert start < end. Have a look at the documentation.

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