java – "if" with a "matches()" or multiple comparisons?

Question:

Considering that I have a variable of type String tipoResidencia type String tipoResidencia that will never be null, and that I need to run a test, the default solution is this:

if (tipoResidencia.equals("CASA") || tipoResidencia.equals("PREDIO") )

But if I want to use matches(regex) to reduce the code would I be doing wrong? Example:

 if (tipoResidencia.matches( "CASA|PREDIO") )

Answer:

Some people might disagree, but for me RegEx only as a last RegEx . In this specific case I think everyone would agree that the first way is simpler to execute.

I don't think the fact that the second form is shorter justifies its use. Being shorter does not necessarily mean being better or more readable.

Anyway, when the two results are the same, there are no side effects, situations where it can cause problems, they are not harmful in any way, choose which one you like best. I choose the simplest one , which in this case is the most basic, the one that everyone recognizes.

Probably two values ​​is the limit of what pays off. If I had multiple values ​​to evaluate, I would probably create a method to simplify and avoid RegEx (then not everyone would agree with me). Then internally I would see how to better solve the list, if its parameter would be a string or an array (most likely). It would be more performant than RegEx .

Scroll to Top