Given e.g. a class instance of some sort has a state (e.g. 'active', 'inactive', …). The instance also attaches a click event to e.g. a link but the event handler does something different depending on the instance's state.
Pseudo code:
IF instance state IS 'active' AND link is clicked THEN call function A
IF instance state IS 'inactive' AND link is clicked THEN call function B
…
I'm wondering what's considered good practice to handle this case properly:
- Which patterns are commonly in use to achieve this?
- Are you using a conditional in the event handler?
- Or are binding and unbinding handlers when the state changes?
- Am I missing some obvious other/better solution?
UPDATE
While reading the answers so far, there seems to be a strong tendency towards the usage of a conditional within the handler. While I had secretly hoped that I might have missed an alternative, I've sort of expected this.
I like @J-P's approach since it keeps the pairing of method and state separately, which seems more scaleable and maintainable than a simple switch
or if/else
statement.
However, I'd be very interested to hear if this is solved differently elsewhere, maybe using an example from a different language?