Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare pattern object as static

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

like image 636
Thomas Buckley Avatar asked Jul 18 '11 10:07

Thomas Buckley


People also ask

Why should we avoid using static for everything?

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.

Can a pattern be static Java?

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).

Can object be made static?

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() { ... } }

Why we should not use static variables in Java?

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.


1 Answers

Yes, it is best if you declare it as static, in order to avoid performance penalties due to the pattern recompiling each time.

like image 91
SJuan76 Avatar answered Sep 18 '22 05:09

SJuan76