calipo909
calipo909

Reputation: 21

How to put a limit on the value of attributes Java

Example:

public class Date {
 private int Day;
 private String Month;
 private int Year;
}

How can I do it so in order once a date is set possible values of day may only be from 1 to 31 and month from jan to december, and only those values are accepted.

Upvotes: 0

Views: 3271

Answers (2)

Jaco Van Niekerk
Jaco Van Niekerk

Reputation: 4192

Since the fields are private, you can check for validness in the setters. For example:

public void setMonth(int month) {
    if (month < 1 || month > 12) {
        throw new IllegalArgumentException(month + " is not a valid month. Month must be between 1 and 12 inclusive";
    }
    this.month = month;
}

Another pattern is the builder pattern, which has a few flavors, including:

public Date withMonth(int month) {
    if (month < 1 || month > 12) {
        throw new IllegalArgumentException(month + " is not a valid month. Month must be between 1 and 12 inclusive";
    }
    this.month = month;
    return this;
}

The above have the advantage of creating objects in one line:

Date myDate = new Date().withMonth(6).withDate(6).withYear(1976);

On another note, it is convention to start variable names with a small letter and use camel casing. Class names would start with a capital and constants (enums and static finals) should be all uppercase with underscore to improve readability.

Upvotes: 5

Arturo Seijas
Arturo Seijas

Reputation: 302

I guess you could use JEE Bean Validation. Take a look at the docs:

You can achieve what you want using annotations @Max and @Min

Upvotes: 0

Related Questions