Once all the data checking classes have been appropriately created, defining a form observer class is indeed a no-brainer process which can be performed quite easily. To put it simply, the form observer class I'm just about to create will perform the following tasks: first, it will check for all the notifications received from the respective form validation classes, and then it will show either a confirmation message (if the data entered on the form doesn't contain errors) or redisplay the form in question. In the latter case, the user can correct the information and resubmit it. Based on the previous explanation, you can understand how the Observer pattern is applied here. First, I have a set of independent classes, where their scope is clearly delimited by the type of data that they have to validate, and second, there is a form observer class which takes all the notices sent by these classes and determines the best action to take. Are you beginning to see how an observer object works in the context of this particular application? Okay, that's a bit of theory. Now, take a look at the definition of the "FormObserver" class: // class FormObserver As you can see, the "FormObserver" class defined above is extremely understandable. Undoubtedly, the most important method worth examining here is "checkNotifications()," which checks for the existence of error messages submitted by the respective validation classes and decides what course of action should be taken. If the data entered into the form is correct, then a confirmation message is presented to the user. If any errors were found during the validation process, the form is redisplayed by calling the "displayForm()" method. In this specific example, I decided to use a form composed of only three text fields, but you can modify this condition by coding a new form, or even using a completely independent class for generating all the form elements. Due to the native extensibility of this form observer class, it can be expanded rapidly. Fine, at this point I hope that you've grasped how a form observer class can be created with minor hassles, which leads directly to decoupling the corresponding data validation classes from the rest of the application. At the same time, this class allows you to implement a centralized mechanism for reflecting all the errors that happened when validating the form in question. This is how an observer works, according to the theory you learned in the course of the previous articles. Having illustrated the corresponding definition for the previous "FormObserver" class, the next step rest on demonstrating how a simple form can be validated by using this class. Regarding this topic, in the next section I'll set up a simple example, which will teach you how the Observer pattern's theory can be translated into fully functional code. Please click on the link below and keep reading to find out how this will be done.
blog comments powered by Disqus |