Pergunta

suppose i have two functions, boolean fA() and boolean fB()

if i write another function function(boolean b) and I call function(fA()||fB()) then fB() might not be executed, if fA() returns true.

I like this feature, but here I need both functions to execute. Obvious implementation:

boolean temp = fA();
function(fB()||temp);

is ugly, and needed extra line makes it less readable.

is there an way to force evaluation in Java or other elegant way to write this in one line without helper variable?

Foi útil?

Solução

You can use | instead, it doesn't do short-circuit evaluation:

function(fB() | fA());

This ensures that even if fB is true, fA will be called.

Outras dicas

You are attempting to write some clever code. This will hurt the long term maintainability and may lead to people trying to 'fix' your clever code and break it.

The correct thing to do is to write it simply and clearly what you are doing:

boolean val = false;
val |= fA();
val |= fB();
function(val);

There is no question what the parameter val is, or if fB() is being called when fA() return false. The code may take up a few more lines than other clever versions, but it is clear and concise and shows exactly what it is doing and intends to do in a way that does not suggest to someone some other functionality.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top