|
Helping ordinary people create extraordinary websites! |
Java Validation With Dynamic ProxiesBy Eric Olson2005-05-14
The dynamic proxy approach Dynamic proxies are classes that implement a set of interfaces specified at runtime. Method invocations on a proxy class are dispatched to an invocation handler that is specified when the proxy class is generated. Dynamic proxy classes have many interesting uses within an application, one of which is to effectively handle pre- and post-method invocation operations in a uniform fashion. Because validation is often a pre-method invocation operation, dynamic proxies provide us with a solution to the problems outlined in the previous examples. Dynamic proxy classes give us a way to easily handle validation on any method in a uniform way, while completely separating all of the validation logic from the core business logic. Because interfaces already exist for the main business objects and services in many frameworks, you've likely had experience with swapping in and out different implementations of such interfaces. Using dynamic proxy classes is very similar, but instead of dealing directly with an implementation of the interface, clients deal with a proxy class that implements the interface, performs the desired validation, and delegates method calls through to an implementation class. With the dynamic proxy approach, all validation logic should be transparent to the clients of the proxied classes. As a result, implementing the new validation scheme should be fairly simple: I won't need to change a single line of the code that uses the User interface. Conceptually, I'll create a custom invocation handler class that performs the validation rules. The invocation handler will contain an instance of a real implementation class as an instance variable. It will first validate method parameters upon a method invocation and then delegate the method call to the implementation class. When the application needs a business object instance, it will actually receive an instance of the dynamic proxy class. As you'll see in a moment, this allows the business object implementation class to remain completely independent of any code specific to the validation processes. A note about interfaces Dynamic proxy classes are generated with a list of interfaces to implement. For the purposes of this article, I'll use the User interface, although generally, you'll need to be sure that you've defined interfaces for any of the methods you want validated this way. Tutorial Pages: » Decouple validation processes from your business object implementations » Tightly coupled validation » Loosely coupled validation » The dynamic proxy approach » The invocation handler » The business object implementation » The business object factory » Drawbacks of dynamic proxies » Other uses for dynamic proxies » Conclusion » Resources First published by |
|