It is not a coding question but related to coding concept. I have a service class with some methods and also this class have following 2 private method for url parse and validation process.
private boolean isUrlFormatValid(String url) {
Pattern pattern = Pattern.compile("^(https?:\\/\\/)?(www\\.)?([\\w]+\\.)+[\u200C\u200B\\w]{2,63}\\/?$");
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
return true;
} else {
LOG.error("Url format is not valid");
return false;
}
}
private String parseUrlDomain(String url) throws Exception {
Pattern p = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.)?((?:[\\w]+\\.)+\\w+)");
Matcher m = p.matcher(url);
if (m.matches()) {
System.out.println(m.group(1));
return m.group(1);
}
throw new Exception("Url domain is not parsed ");
}
These codes are working good but i am not sure about some points like:
1-As you see both method has common codes, creating pattern and matcher instances. Should i create instance of them at the beginning of class as global variable? If so what is the reason for it and what is the advantage of it.
2-In case of an error, i am not sure which one is better; throw exception as in second method or just log the error and continue as in first method.
Hence is there any best practise for it ? Thanks in advance.