Redundant logic
The initial
if (employeeNumber.length() == 0) {
return false;
}
is not needed. If the string is empty, your loop will never execute and counter
will be 0 after it, so the code would return
false
anyway.
Performance
This code
counter = counter + Integer.parseInt(String.valueOf(employeeNumber.charAt(i)));
is a very expensive and convoluted way to check whether employeeNumer
has a decimal digit at position i
.
I'd use something like this instead.
final char c = employeeNumber.charAt(i);
if ((c < '0') || (c > '9')) {
return false;
}
counter += c - '0'; // Add numerical value of the character
This works because Java's strings are Unicode and your input only allows digits anyway.
Error Handling
You should almost never do this:
catch (Exception someException) {
…
}
What kind of exception do you expect to be throw
n from within your try
block? The only possibility I can see is a NumberFormatException
if Integer.parseInt
is given something that is not an integer representation. Any other exception you'll catch
will be camouflaging some serious problem.
- A bug in your own code, such as an indexing error in the iteration over the characters of the string.
- Misuse by your clients, for example, passing in
null
as employeeNumber
.
- Serious errors in the run-time environment (unlikely in this case).
You shouldn't catch
any of these.
If you omit the Integer.parseInt
call as suggested above, there won't be any need for a try { … } catch { … }
at all any more, which is a good thing.
Code formatting
Consider using more spaces even where they are not strictly required lexically. Most people will find
for (int i = 0; i < employeeNumber.length(); i++) {
easier to read than
for(int i=0;i<employeeNumber.length();i++){
and it is pretty much agreed upon style.
Also try to be consistent with your use of braces for single statements. Currently, you are sometimes using braces around the single statement of a control-flow construct…
if(employeeNumber.length()==0){
return false;
}
…and sometimes you are not.
if(counter==0)
return false;
I don't really care which style you're using but it should be consistent. From what I can tell, most Java programmers seem to prefer to always use braces, even when not strictly required.