Usuage of one of the principle of object oriented programming Tell, dont' ask was narrated with an example.
In MVC architecture, the controller takes the data input from the model object, process the same and re-directs to a view.
Consider a scenario whereby the server has to kill the expiring client sessions. Each of the sesssion object will have the last accessed time. The controller is the one has to kill the expiring client sessions.
In this context, the computational logic used is (current time - last accesssed time >500). This needs to be placed in following places.
Case I: Controller
If the computation logic is placed in the controller, the contoller takes the input (last accessed time) from the session object and applies the computational logic and decides whether the session needs to be killed. If the condition is true, it sets session timeout(kills).
Case II: Model
Computational logic can be placed at the model object. Whenever the controller asks whether the session is alive or not, controller can just take the computed information and then decides whether to kill the object or not.
But in this scenario, there is question of what would be the ideal choice?
Here comes the oops Tell, don't ask principle as a rescue. It suggests not to expect (don't ask) the controller to do the work of computation of business logic, for the determination of whether the session needs to be kept alive or not. In order to acheive this, let the model object do the computation and maintain the status of isAlive. The object maintains both the last acccessed time and also the isToBeAlive status. For the session who has crossed the cutofftime, will still be alive with the isToBeAlive status as false.
In otherwords, session object will be alive until its killed by the controller. Its only the controller has to decide and act (kill) the session object. Now the controller will not ask for the raw data and compute the results. It straight way asks the model object (Tell) for the computed result (isTobeAlive flag)whether object needs to be killed. Based on the result/info from the object, the controller will kill the object.
Conclusion:
Let the model object do the business logic and controller will be free enough to make actions based on the information provided by the model object. Always it would be easier to test the method/business logic by overriding the methods through junits.
Its always encourageous to see your views/perspectives.
Friday, March 21, 2008
Subscribe to:
Comments (Atom)