add constraint for variables in java

Viewed 143

Can I directly add constraint to the variables to make it impossible to create a new object, if the new object's attributes must meet certain condition. The following part, I wish automatically check that lowerbound <=upperbound. or other something like int lowerBound is larger that 0. In Database, we have check constraint. So I wonder in Java:

import java.math.*;

public class SumAverageRunningInt {
    private int lowerBound;
    private int upperBound; 

    public SumAverageRunningInt(int lowerBound, int upperBound) {
        this.lowerBound = lowerBound;
        this.upperBound = upperBound;
    }


    public int getlowerBound() {return lowerBound;}
    public int getupperBound() {return upperBound;}
    

    public int sum() {
        int sum = 0;
        int i = 0;
        int a = this.getlowerBound();
        int b = this.getupperBound();
        while (a<=b) {
            sum = a + sum;
            a = a + 1;}
        return sum;
       }    
}
1 Answers

Have a look at PreConditions class in Guava.

Add this dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>29.0-jre</version>
</dependency>

Then use it as such:

import static com.google.common.base.Preconditions.checkArgument;

public SumAverageRunningInt(int lowerBound, int upperBound) {
    checkArgument(lowerBound <= upperBound, "lowerBound should be smaller or equal than upperBound");
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
}

If you don't want to add third-party libraries (for such small task is not really necessary), you may implement the check yourself:

public static void checkCondition(boolean condition, String errorMessage) {
    if (!condition) {
        throw new IllegalArgumentException(errorMessage);
    }
}

public SumAverageRunningInt(int lowerBound, int upperBound) {
    checkCondition(lowerBound <= upperBound, "lowerBound should be smaller or equal than upperBound");
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
}
Related