if with a Matches or multiple comparisons?

Asked

Viewed 197 times

9

Whereas I have a variable of the 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") )

1 answer

9


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

I do not think that 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 equal, there are no side effects, situations where you can give problem, they are not harmful in any way, choose which pleases you most. I I choose the simplest, which in this case is the most basic, the one that everyone recognizes.

Probably two values is the limit of what compensates. If I had several values to evaluate, I would probably create a method to simplify and avoid the 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 a array (most likely). It would be more performatic than RegEx.

  • I like the reference!

  • Another thing I can suggest is: even if you know that the String you are using will not be null, adopt the "HOME" pattern. equals(type) ... so in other situations you can avoid a Nullpointerexception

  • 1

    @Pedrolaini agree, with your tip tambe, we can use if ( Boolean.false.equals(variavelBoolean) ) for variables of the Boolean type

Browser other questions tagged

You are not signed in. Login or sign up in order to post.