saoj
Joined: 22/12/2007 07:20:02
Messages: 22
Offline
|
Because validation is dynamic, in other words, the validation code is executed per each request, you should avoid creating new rule objects inside your validation code. Check the code below:
The code above is perfectly correct and legal, but we are creating too many new objects on each request without a real need for it. A rule is thread-safe by design and you should re-use the same instance across different requests. A possible fix for this problem is illustrated in the code below:
However note that it is not very easy to read the validation code when the rules are defined outside the prepareValidator() method. A better approach is to make the rule constructor private and create a static getInstance() method that will return instances of the rule and it will be smart enough to return the same instance when the same object is requested. Check below how we would accomplish this with the NegativeRule introduced in the previous chapter.
Check how we are using a cache to return the same instance for each "min" parameter passed to the getInstance() method. This will avoid creating unnecessary duplicates of the same object.
Most of the provided rules inside the org.mentawai.rule package implement the getInstance() method. So when using them you should make use of this method to obtain instances of the rule. Check the example below:
When coding your own rules, you should provide a getInstance() method whenever possible. But this is not really a necessity. It is just a good practice that it is worth mentioning for the competent programmer.
|