if with a matches or several comparisons?


Considering that I have a variable of 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 be doing wrong? Example:

 if (tipoResidencia.matches( "CASA|PREDIO") )
asked by anonymous 14.08.2015 / 22:14

1 answer


Some people may disagree but for me RegEx only in the last case. In this specific case I think everyone would agree that the first form is simpler to execute.

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

Finally, when the two results are the same, it has no side effects, situations where it can be a problem, they are not harmful in some way, choose which one pleases you the most. I I choose the simplest , which in this case is the most basic, which everyone recognizes.

Probably two values is the limit of what pays off. If I had several values to evaluate, I would probably create a method to simplify and avoid RegEx . I would then internally see how to best sort the list, whether its parameter would be a string or an array (most likely).

14.08.2015 / 22:25