0

So I want to make a social security class, and the input has to be in the following format

# # # - # # - # # # #

This is a string, and in my constructor i have the following code to check if its a proper method.

private static boolean checkSocialSecurityNumber(String s) {
        int positionOfFirstDash = 3;
        int positionOfSecondDash = 6;
        if(s.length() != 11) {
            return false;
        }
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(i == positionOfFirstDash || i == positionOfSecondDash) {
                if( c != ('-')){
                    return false;
                }
            }
            else if(!Character.isDigit(c)) {
                return false;
            }
        }

        return true;
    }

}

This method works, but its inside the classes constructor declaration.

and I would throw a system error if it returns false.

Is this the proper way to do it? it just looks wrong to have that in my constructor. My question is how I go about forcing the proper input, not sure how else to do it?

DDisciple
  • 177
  • 1
  • 10
  • You might consider using a regular expression for this validation. – khelwood Apr 24 '19 at 13:20
  • 2
    "this method works, but its inside the classes constructor declaration" ... what? – Stultuske Apr 24 '19 at 13:21
  • Please specify what "good" means in your case. – Lajos Arpad Apr 24 '19 at 13:22
  • For me, doing the check within the constructer seems ok. I don't have any literature references but in my opinion it makes sense to check it directly inside the constructor since this is the "place" where you create/not create an object. – Stephan Pillhofer Apr 24 '19 at 13:23
  • Yes it is a good practice to check the if the argument given to your constructor is correct. Plus there is no problem to call a subroutine inside a constructor. And finally, throwing an exception if the argument given does not fit the requirement is also a good practice. Conclusion : Your code is totally OK – vincrichaud Apr 24 '19 at 13:25
  • @vincrichaud "no problem" not necessarily. You can invoke a method before fields it uses have been initialized. It's also problematic to invoke any overrideable method. – Andy Turner Apr 24 '19 at 14:26
  • Also, and I don't often say this: your method would be much easier with regex: `s.matches("\\d{3}-\\d{2}-\\d{3}")`. – Andy Turner Apr 24 '19 at 14:30

0 Answers0