4

How would check for an input error in initializing a class in java? I've included an example

public class Date {
private int d;
private int m;
private int y;    

public Date(int d, int m, int y) {
    if(is valid date){
      this.d = d;
      this.m = m;
      this.y = y; //etc
    } else {
      //  ??????
      // throw an exception?
    }   
  }
}
1
  • In case you need data verification I suggest the Builder pattern or a factory method instead Commented Nov 16, 2014 at 19:34

4 Answers 4

2

You could go several ways I suppose:
- You can simply throw an Exception - think about whether or not you want to go with Checked or Unchecked Exceptions

-You could do something like denispyr suggested.

public class Date {
    private int d;
    private int m;
    private int y;    

public static Date createNewDate(int d, int m, int y) throws IllegalArgumentException {
     // your checks here

     return new Date(int d, int m, int y);
}

private Date(int d, int m, int y) {
    this.d = d;
    this.m = m;
    this.y = y; //etc
  }
}

You could declare exceptions in your create Method.

Check out these links: - Is it good practice to make the constructor throw an exception? - Can constructors throw exceptions in Java?

So if none of the points of the second link (resource allocation in constructor, finalizer attack) I guess there is nothing wrong with throwing in the constructor.

Sign up to request clarification or add additional context in comments.

Comments

1

I would do something like this:

import java.io.IOException;
public class Date() {
    private int d, m, y;
    public Date(int d, m, y) throws IOException {
        final int currentYear=2014;
        if (d<0||m<0||y<0||d>31||m>12||y>currentYear) throw new IOException();
        //will exit if there is illegal input
        this.d=d;
        //et cetera
}
}

Note: It is highly recommended that you actually throw an error, instead of trying to make do with bad input, because chances are, the programmer who gave you bad input will want to know what it was and try to fix it because the program is probably doing something other than what he thinks it is.

1 Comment

What if the month is April and the day is 31 ? That should be an illegal date!
0
static ArrayList<Integer> monthsWithThirtyDays=new ArrayList<Integer>(Arrays.asList(new Integer[]{1,3,5,7,8,10,12}));

private int d, m, y;

public static boolean isValidDate(int d, int m, int y) {
    if(y<=0) // Year can't be below or equal to 0
        return false;

    if(!(m>0 && m<=12)) // Month can't be under 0 or above 12
        return false;

    if(monthsWithThirtyDays.contains(m)) { // If the month has 30 days
        if(!(d>0 && d<=30))// Day can't be below 0 or above 30
            return false;
    } else if(m==2){ // If the month is February
        if(y%4==0) { // If it has 29 days
            if(!(d>0 && d<=29)) //Day can't be below 0 or above 29
                return false;
        } else { // If it has 28 days
            if(!(d>0 && d<=28)) // Day can't be below 0 or above 28
                return false;               
        }
    } else { // If the month has 31 days
        if(!(d>0 && d<=31)) // Day can't be below 0 or above 31
            return false;
    }

    return true;
}

public Date(int d, int m, int y) throws Exception {
if(isValidDate(d,m,y)) {
    this.d=d; this.m=m; this.y=y;
} else {
    throw new Exception();
}

}

This also deals with the 29th day of February every 4 year.

Let me know if it works (or not)
Happy coding :) -Charlie

Comments

0

you can use parse method of SimpleDateFormat class to check whether date is valid or not. parse method will throw ParseException if date is not valid.

public class Date {
private int d;
private int m;
private int y;    

public Date(int d, int m, int y) throws ParseException {
      String dateToValidate = y+"-"+m+"-"+d;

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      sdf.setLenient(false);
      Date date = sdf.parse(dateToValidate);

      this.d = d;
      this.m = m;
      this.y = y;

  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.