What’s the common approach (or design pattern) for this “problem” :
- I have a lot of controllers in a web application (struts actions in
JAVA to be precise). - Some controllers sets variables in the user’s session.
- Some controllers use those variables, remove them, modify them,
etc…
It’s messy because it’s hard to know who set what, in what condition, where it changes…
Should I use the Mediator pattern :
http://en.wikipedia.org/wiki/Mediator_pattern
Or the Facade pattern like this (example in c#) :
http://foxsys.blogspot.ca/2007/01/session-facade-aspnet-c.html
Or something else?
Example of the workflow of a variable and how it can be messy :
-
The user choses a preferred product. The ChooseProductController sets the id of the preferred product in session
-
The user creates an account : The CreateAccountController checks if a preferred product is in session. If it’s the case, it creates the account in DB with this id
-
The user is logged in. The LoginController checks if a preferred product is in session. If it’s different from the one in DB when the account was created, the view needs to display a message to ask the use to choose the preferred product.
First advice: use the session as seldomly as possible. Try to only use it for things that have a lifetime identical to the lifetime of the session, and that can’t be retrieved from the database easily or fast enough.
Second advice: don’t use the session directly. Encapsulate the access to the session in one or a few dedicated class(es) (like you would do for a database, except the session is an in-memory database). Instead of doing
, do something like
This is more readable, much less error-prone, and allows finding easily in all the codebase where the preferred product is get or set.