I have the following method in a class:
public boolean validTransAmt()
{
FacesContext facesContext = FacesContext.getCurrentInstance();
Pattern p = Pattern.compile("^([0-9]{0,})(([\\.]?)([0-9]{1,2})([\\.]?))$");
String transAmt = getDetails().getAmount();
Matcher matcher = p.matcher(transAmt);
if (!matcher.matches())
{
...
}
...
}
Will this pattern get re-compiled every time the method is called? Or does it get cached?
Should I declare it as a static variable in my class?
Thanks
Static methods aren't part of the object, so they don't have access to anything that belongs to the object. Instead, they belong to the underlying class of the object. Hence, static methods can only access static variables - and we've already declared them taboo.
Java Pattern objects are thread safe and immutable (its the matchers that are not thread safe). As such, there is no reason not to make them static if they are going to be used by each instance of the class (or again in another method in the class).
Objects are never static. You can create classes, which are kind of, let's say, blueprints of an object: public class Aa { public void doSomething() { ... } public static void doMore() { ... } }
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Yes, it is best if you declare it as static, in order to avoid performance penalties due to the pattern recompiling each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With