3
\$\begingroup\$

I have a method like this:

public boolean wasUserInactive() {
    boolean result = userInactive;
    userInactive = false;
    return result;
}  

This works, but is there a “smarter” way to code this?

\$\endgroup\$

1 Answer 1

12
\$\begingroup\$

This method satisfies two concerns:

  1. mark users as active
  2. return the last status of inactivity

This should be two separate methods so as to not violate SRP and enable checking of that status without resetting it.

wasUserInactive should be isUserInactive and just return userInactive;. Additionally there should be a method resetting the inactive status to false.

Don't introduce quantum behaviour in your code, where observing a state changes it!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.