Return statement with integrated logic

I know this is probably a very simple question, but I came across this in some code in the project today. How does the return statement work? What kind of operation is this? Is it compatible with the tertiary operator?

Access to a variable is int.

return access != IACL.RS_NOACCESS && documentVersion >= 0; 
+4
source share
3 answers

Let it be broken using parentheses to make logical groupings explicit:

 return ((access != IACL.RS_NOACCESS) && (documentVersion >= 0)); 

Thus, the method returns a logical value, the result of comparisons. The entire expression is evaluated before the value of the expression is returned.

Suppose access is IACL.RS_NOACCESS and documentVersion is 1 . Then the statement boils down to:

 return ((IACL.RS_NOACCESS != IACL.RS_NOACCESS) && (1 >= 0)); 

and it is rated as:

 return ((false) && (true)); 

and it is rated as:

 return false; 

One important point Ryan pointed out in a comment: logical operators like && and || are short-circuited in most languages, in most scenarios. They are in Java. This means that the score comes from left to right. If it makes no sense to evaluate the second part of the expression, then it will not be evaluated.

In the above case, since the first part of the expression evaluates to false, it does not matter what the second part of the expression evaluates - given the AND truth table, the full expression will always be evaluated as false. In fact, you can have an expression that generates a runtime error on the right side - it doesn't matter. With these values, the right side will never be launched.

+8
source

The entire expression to the right of return is evaluated as a boolean that is returned.

 return access != IACL.RS_NOACCESS && documentVersion >= 0; 

It is equivalent to:

 boolean result = (access != IACL.RS_NOACCESS); result = result && (documentVersion >= 0); return result; 
+5
source

This is equivalent to:

 boolean valid = access != IACL.RS_NOACCESS && documentVersion >= 0; return valid; 

It simply excludes the variable since there is no need to store the result access != IACL.RS_NOACCESS && documentVersion >= 0 . It’s just saving space, basically.

+2
source

Source: https://habr.com/ru/post/1482239/


All Articles